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:
@Component({ selector: 'app-one', template: ` <div> <h1 #one>Hello from One!</h1> <ng-content></ng-content> </div> `})export class OneComponent {...}
@Component({
selector: 'app-one',
template: `
<div>
<h1 #one>Hello from One!</h1>
<ng-content></ng-content>
</div>
`
})
export class OneComponent {...}
Two Component:
@Component({ selector: 'app-two', template: ` <app-one> <h2 #two>Hello from Two!</h2> </app-one> `})export class TwoComponent {...}
selector: 'app-two',
<app-one>
<h2 #two>Hello from Two!</h2>
</app-one>
export class TwoComponent {...}
Now if I wish to select h1 element from OneComponent. I’ll use ViewChild.
@ViewChild('one') public headingOne;
And I can access this element using AfterViewInit hook.
ngAfterViewInit() { console.log(this.headingOne);}
ngAfterViewInit() {
console.log(this.headingOne);
}
And if I want to select h2 element (Projected Content) from OneComponent I need to use ContentChild.
@ContentChild('two') public headingTwo;
And I can access the h2 element using AfterContentInit hook.
ngAfterContentInit() { console.log(this.headingTwo);}
ngAfterContentInit() {
console.log(this.headingTwo);
Note: #one and #two are template reference variables.