What is the difference between functions ngAfterContentInit()
and ngAfterViewInit()
?
ngAfterViewInit is useful when you want to call a lifecycle hook after all child components have been initialized and checked.
ngAfterContentInit()linkA callback method that is invoked immediately after Angular has completed initialization of all of the directive's content. It is invoked only once when the directive is instantiated.
ngAfterViewInit()linkA callback method that is invoked immediately after Angular has completed initialization of a component's view. It is invoked only once when the view is instantiated.
ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated. ngAfterViewInit() is called after a component's view, and its children's views, are created.
Content is what is passed as children usually to be projected at some <ng-content>
element of a component.
View is the template of the current component.
The view is initialized after the content and ngAfterViewInit()
is therefore called after ngAfterContentInit()
.
@Component({ selector: 'parent-cmp', template: '<div #wrapper><ng-content></ng-content></div>' }) class ParentComponent { @ViewChild('wrapper') wrapper:ElementRef; @ContentChild('myContent') content:ElementRef; ngAfterViewInit() { console.log('ngAfterViewInit - wrapper', this.wrapper); console.log('ngAfterViewInit - content', this.content); } ngAfterContentInit() { console.log('ngAfterContentInit - wrapper', this.wrapper); console.log('ngAfterContentInit - content', this.content); } }
<parent-cmp><div #myContent>foo</div></parent-cmp>
If you run this code, the output for ngAfterViewInit - content
should be null
.
More details about lifecycle hooks see https://angular.io/guide/lifecycle-hooks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With