What is the difference between ngAfterViewInit() and ngAfterViewChecked()?
The best article out there that explains lifecycle hooks in details is Everything you need to know about change detection in Angular.
ngAfterViewInit Vs ngAfterVIewChecked
As explained in the article the ngAfterVIewChecked
is called every time Angular has finished running change detection on a component and it's children. ngAfterViewInit
is called only during first change detection cycle. You can use it if you need to know when the first change detection cycle runs. For example, you need to setup listeners for some jQuery elements and you need to wait until they are initialized:
ngAfterViewInit() {
this.widget = $(this.location.nativeElement).slider({value: this.value});
this.widget.on('slidestop', (event, ui) => {
this.onChange(ui.value);
});
}
The same holds for ngAfterContentInit
with the difference that Angular runs change detection for projected content (through ng-content
) instead of the children specified in the components template.
I can't understand what that word "Checked" mentioned?
Checking means running change detection and performing change detection related operations like DOM update, querylist update and child component bindings update.
You can refer to the docs which clearly states of these:
ngAfterContentInit()
Respond after Angular projects external content into the component's view. Called once after the first ngDoCheck().
ngAfterContentChecked()
Respond after Angular checks the content projected into the component. Called after the ngAfterContentInit() and every subsequent ngDoCheck().
ngAfterViewInit()
Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked().
ngAfterViewChecked()
Respond after Angular checks the component's views and child views. Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
That means Checked
states to say it runs after Init
. Initialization means it runs at first and Checking for the changes runs many times after initialization.