Kiran Mohanty
What is the difference between @ViewChild and @ContentChild ?
By Kiran Mohanty in Angular on Nov 12 2020
  • Harshal Limaye
    Dec, 2020 24

    ViewChild is used to select an element from component’s template while ContentChild is used to select projected content.

    Let’s say I have two components.

    One Component:

    1. @Component({
    2. selector: 'app-one',
    3. template: `
    4. <div>
    5. <h1 #one>Hello from One!</h1>
    6. <ng-content></ng-content>
    7. </div>
    8. `
    9. })
    10. export class OneComponent {...}

    Two Component:

    1. @Component({
    2. selector: 'app-two',
    3. template: `
    4. <app-one>
    5. <h2 #two>Hello from Two!</h2>
    6. </app-one>
    7. `
    8. })
    9. export class TwoComponent {...}

    Now if I wish to select h1 element from OneComponent. I’ll use ViewChild.

    1. @ViewChild('one') public headingOne;

    And I can access this element using AfterViewInit hook.

    1. ngAfterViewInit() {
    2. console.log(this.headingOne);
    3. }

    And if I want to select h2 element (Projected Content) from OneComponent I need to use ContentChild.

    1. @ContentChild('two') public headingTwo;

    And I can access the h2 element using AfterContentInit hook.

    1. ngAfterContentInit() {
    2. console.log(this.headingTwo);
    3. }

    Note: #one and #two are template reference variables.

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS