I have been trying to figure out the meaning of ngAfterContentChecked()
and ngAfterViewChecked()
for some time. Have tried various posts, but still can't understand their exact meaning. Following is the definition given in angular.io.
Can somebody explain it properly with some goood example.
ngAfterViewChecked()- Respond after Angular checks the component's views and child views.
Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
A component-only hook.
ngAfterContentChecked()- Respond after Angular checks the content projected into the component.
Called after the ngAfterContentInit() and every subsequent ngDoCheck().
A component-only hook.
A callback method that is invoked immediately after the default change detector has completed checking all of the directive's content.
ngAfterContentInit : This is called after components external content has been initialized. ngAfterViewInit : This is called after the component view and its child views has been initialized.
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.
Lifecycle sequence Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges() . Detect and act upon changes that Angular can't or won't detect on its own.
Let's say we have this Html
<div> // div A
<app-my-component>
<div>
this is some content for the component app-my-component
</div>
</app-my-component>
</div> // div B
Let's say we have this component
@Component({
selector: 'app-my-component',
template: `
<div> // div C
here is the View HTML but below we receive content html
<ng-content></ng-content>
</div> // div D
`
})
In our component from div A all the way through div B that is the View. So AfterViewChecked will run when we reach B. The content is everything that resides in the ng-content tag. So AfterContentChecked will run when we reach div D. However any and I mean any changes to the view can trigger an additional AfterViewCheck which should also trigger an AfterContentCheck
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