Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ngAfterContentInit() and ngAfterViewInit()?

Tags:

angular

What is the difference between functions ngAfterContentInit() and ngAfterViewInit()?

like image 673
Dariusz Filipiak Avatar asked Jun 22 '16 08:06

Dariusz Filipiak


People also ask

When should you use ngAfterViewInit?

ngAfterViewInit is useful when you want to call a lifecycle hook after all child components have been initialized and checked.

What does the ngAfterContentInit () method do?

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.

What is the use of ngAfterViewInit in Angular?

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.

What is the difference between ngOnInit and ngAfterViewInit?

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.


1 Answers

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

like image 131
Günter Zöchbauer Avatar answered Sep 21 '22 18:09

Günter Zöchbauer