Home Angular Tutorials ngAfterContentChecked lifecycle hook in angular

ngAfterContentChecked lifecycle hook in angular

by aouidane.med.amine
187,179 views 25 min read

In this tutorial , we are going to see how to use ngAfterContentChecked lifecycle hook in angular and when angular exactly invokes the callback.

Also , we are going to see the difference between ngAfterContenChecked and ngAfterContentInit lifecycle hooks through a simple example.

Table of Contents

Angular Lifecycle Hooks

Angular has 8 lifecycle hooks, but in this tutorial, we will cover only the ngAfterContentInit lifecycle hook

What is ngAfterContentChecked lifecycle hook ?

ngAfteContentChecked lifecycle hook is a simple callback which gets called by angular after the change detector completes the check of the directive’s content ( the directive could be a simple child component ).

Like any other lifecycle hook , ngAfterContentChecked is invoked by angular depending on its priority index.

in our case , ngAfterContentChecked lifecycle hook will be invoked after 4 lifecycle hooks (ngOnChanges,ngOnInit,ngDoCheck,ngAfterContentInit).

The ngAfterContentChecked lifecycle hook is a little bit similar to the ngAfterContentInit lifecycle hook. both of them are used when we handle the content projection

but the important difference is the number of times that angular invokes the callback.

ngAfterContentInit is called only one time when we load the component ,meanwhile ngAfterContentChecked lifecycle hook is called every time we make changes in the view (button click ,input change .. ). 

So , we can say that ngAfterContentChecked lifecycle hook is called every time when angular has completely checked all the directive’s content.

How to use the ngAfterContenChecked lifecycle hook ?

To correctly use the ngAfterContentChecked lifecycle hook we just need to implement the AfterContentChecked interface and use the callback method in the component like any other lifecycle hook.

Note that implementing the lifecycle hook is optional because angular calls immediately the lifecycle methods when it finds them in the component , despite that it is very recommended to implement the interface to keep a clean code.

Syntax :

				
					@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    // ...
  }
}
				
			

ngAfterContenChecked lifecycle hook Example

In this section , we are going to make a little example to check when angular invokes ngAfterContentChecked lifecycle hook

To use the content projection in our example we are going to create a parent component and child component ( the child component could be any directive)

We are going to start by creating the parent component.

In the parent component template , we are going to inject the child component with a custom content using the content projection concept.

We are going to update the projected content for every button click to see when angular calls ngAfterContentChecked lifecycle hook.

It is a good opportunity to check also when calling ngAfterContentInit lifecycle hook and see the difference between them.

				
					import {AfterContentChecked, AfterContentInit, Component,} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentChecked, AfterContentInit {

  customDataFromParent = ''

  setCustomDataToChild() {
    let random = Math.floor(Math.random() * 10);
    this.customDataFromParent = 'Custom data from Parent Component ' + random;
  }

  ngAfterContentInit() {
    console.log('ngAfterContentInit was invoked')
  }

  ngAfterContentChecked() {
    console.log('ngAfterContentChecked was invoked')
  }
}

				
			
				
					<div class="mat-card parent-comp">
  <h2> Parent Component </h2>
  <button (click)="setCustomDataToChild()">set Custom Data</button>
  <child-comp>
    <h3> {{ customDataFromParent }}</h3>
  </child-comp>
</div>


				
			

Now , we will create a child component which will be used by the parent to inject dynamic content.

				
					import {Component, DoCheck} from '@angular/core';

@Component({
  selector: 'child-comp',
  templateUrl: './child.component.html',
})
export class ChildComponent implements DoCheck {

  ngDoCheck() {
    console.log('ngDoCheck was invoked from Child')
  }
}

				
			
				
					<div class="mat-card" style="background-color: red">
  <h3>Child component</h3>
  <ng-content></ng-content>
</div>


				
			

We are going to get something like this as a result : 

How to use ngAfterContentChecked lifecycle hook example

When we run the application , and see the logs inside the browser console , we will notice that the ngAfterContentChecked and ngAfterContentInit callbacks were invoked.

Now , when we click the button from the parent to update the projected content with a random number ,

we will notice that only the ngAfterContentChecked callback was invoked.

The example proves that the ngAfterContentChecked lifecycle hook is invoked every time we make changes in the view unlike the ngAfterContentInit lifecycle hook which invoked only once.

References

Recapitulation

Clone The Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/ngAfterContentChecked_lifecycle.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Lifecycle hooks:

You may also like