Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngAfterContentChecked() not understandable + angular 2

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.
like image 233
clint Avatar asked Jun 21 '17 04:06

clint


People also ask

What is Ngaftercontentchecked in Angular?

A callback method that is invoked immediately after the default change detector has completed checking all of the directive's content.

What is difference between ngAfterViewInit and ngAfterContentInit?

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.

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.

What is the correct order of lifecycle hooks in Angular?

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.


1 Answers

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

like image 129
Woot Avatar answered Oct 07 '22 03:10

Woot