Component Lifecycle Hooks in Angular 5 - Part 2

In this article, I am going to explain component’s lifecycle hooks. I have already explained first three hooks ( i.e., OnChange, OnInit and DoCheck) in my previous article Component Lifecycle Hooks in Angular 5.

Let’s start with the remaining hooks.


This is called whenever the content which is projected through ng-content has been initialized, so not the view of the component itself but instead, we can say, the view of the parent component (especially a part of the parent) is added to our component.

Here, content projected means a way to import HTML content from outside the component and insert that content into the content’s template in a designated spot and this spot is identified by Angular with the help of <ng-content>, i.e. it can put the content’s template where <ng-content></ng-content> is present.

Let’s understand this with an example.

Create one more component called “second” using the below command.

ng g c second

Now, let us go to second.component.html file and put the following lines.

  1. <br>  
  2.    Title :- {{title}}  
  3. <br>  

Go to second.component.ts file, and set the value of title.

  1. title: string;  
  2.   constructor() {  
  3.     this.title = "Hello Mahesh!";  
  4.   }  

Go to app.component.ts file.

  1. @Component({  
  2.   selector: 'after-content',  
  3.   template: `  
  4.               <div class="row">  
  5.                 <div class="col-md-4">  
  6.                   <div class="card">  
  7.                   <div class="card-header bg-primary text-white"> ngAfterContentInit () </div>  
  8.                   <div class="card-body">  
  9.                      <div>  
  10.                         <input type="text" />  
  11.                         <ng-content></ng-content><br>  
  12.                       </div>  
  13.                   </div>  
  14.                   </div>  
  15.                 </div>  
  16.               </div>`,  
  17. })  
  19. export class AfterContent implements AfterContentInit{  
  21.   @ContentChild(SecondComponent) contentChild: SecondComponent;  
  22.   ngAfterContentInit() {  
  23.     console.log("After content in it");  
  24.   }  
  26. }  
  28. @Component({  
  29.   selector: 'app-root',  
  30.   template: `<div>  
  31.         <after-content>  
  32.         <app-second></app-second>  
  33.             </after-content>  
  34.         </div>`,  
  35.   styleUrls: ['./app.component.css']  
  36. })  
  38. export class AppComponent {  
  40.   title = 'app';  
  41.   valueFromChild: any;  
  42.  }  

In the above code, we created one more component called "AfterContent" and made it as a parent component for second component. In the aftercontent component, inside the template, we put <ng-content></ng-content> where child content, i.e., the second component can be injected.

Whenever this child component is projected into parent component, it fires ngAfterContentInit(). When we run this code, we will see the following output.


Now, again my question is "what is the benefit of using this?"

So, the benefit is that if we want to change something after the content is loaded, then we can easily change it. For example - if we want to change the title, we change it inside the ngAfterContentInit() hook, like

  1. ngAfterContentInit() {  
  2.   this.contentChild.title = "my first title";  
  3.   console.log("After content in it");  
  4. }  

We have already set the title inside the constructor of second.component.ts file, like -

  1. constructor() {  
  2.     this.title = "Hello Mahesh!";  
  3.   }  

So, the first constructor is invoked but after the content projection, the title will be changed due to ngAfterContentInit() and we will get the following output like,



It is executed whenever the change detection occurs i.e. content will be projecting into our component. It is called immediately after the ngAfterContentInit and after every subsequent ngDoCheck().

Let’s understand with an example.

We are going to create a button and on button click, we will change the value of “AfterContent”. So, whenever this value changes, ngAfterContentChecked() fires.

Go to second.component.html file,

  1. <br>  
  2. Title :- {{title}}  
  3. <br>  
  4. <button class="btn btn-primary" (click)="onClick()">Change</button>  

Write definition for onClick() method inside second.component.ts file

  1. onClick() {  
  2.     this.title = "Value Change";  
  3.   }  

Now, go to app.component.ts file and implement ngAfterContentChecked() inside AfterContent Class, like

  1. export class AfterContent implements AfterContentInit, AfterContentChecked {  
  2.   ngAfterContentCheckedcalled = 0;  
  4.   @ContentChild(SecondComponent) contentChild: SecondComponent;  
  6.   ngAfterContentInit() {  
  7.     this.contentChild.title = "my first title";  
  8.     console.log("After content in it");  
  9.   }  
  11.   ngAfterContentChecked() {  
  12.     this.ngAfterContentCheckedcalled += 1;  
  13.     console.log("After content checked");  
  14.   }  
  15. }  

And inside the AfterContent’s template, display the value of ngAfterConetentCheckedCalled variable like,

  1. template: `  
  2.               <div class="row">  
  3.                 <div class="col-md-4">  
  4.                   <div class="card">  
  5.                   <div class="card-header bg-primary text-white"> ngAfterContentInit () </div>  
  6.                   <div class="card-body">  
  7.                      <div>  
  8.                         <input type="text" />  
  9.                         <ng-content></ng-content><br>  
  10.                         Value Changed :  {{ngAfterContentCheckedcalled}}  
  11.                       </div>  
  12.                   </div>  
  13.                   </div>  
  14.                 </div>  
  15.               </div>`,  

Now, we run into this program,



It is called after the component's view (and child view) has been initialized. It is very similar to ngAfterContentInit, but it works on view that is whenever view is initialize it fires.


It fires after ngAfterViewInit() and every time the view (and child view) have been checked. This hook  is fired after the ngAfterViewInit and after that for every subsequent ngAfterContentChecked hook.

As per the name it both will run with View i.e. whenever view (template) is initialized and if some changes occur.

For understanding the above two, just change into second.component.ts file, like:

  1. ngAfterViewInit(){  
  2.     console.log("After view init");  
  3.    }  
  5. ngAfterViewChecked(){  
  6.     console.log("After value updated");  
  7.   }  


This hook is called once the component or directive is about to destroy. Generally, we put logic related to cleanup here. This is the right place where we would like  to Unsubscribe Observable and detach event handlers to avoid memory leaks.

Lets understand with example :

We go to second.component.html file, and write the following code:

  1. <br>  
  2.    Title :- {{title}}  
  3. <br>  

Go to second.component.ts file and write the following code, inside the class.

  1. constructor() {  
  2.     this.title = "Hello Mahesh!";  
  3.   }  
  5.   onClick() {  
  6.     this.title = "Value Change";  
  7.   }  
  9.   ngOnInit() {  
  10.     console.log('ChildComponent:OnInit');  
  11.   }  
  13.   ngOnDestroy() {  
  14.     console.log('ChildComponent:OnDestroy');  
  15.   } 

Now, go to app.component.ts file and change the template as well as class, in template write the following code:

  1. @Component({  
  2.   selector: 'app-root',  
  3.   template: `<div class="row">  
  4.                 <div class="col-md-4">  
  5.                   <div class="card">  
  6.                     <div class="card-header bg-primary text-white"> ngOnDestroy() </div>  
  7.                     <div class="card-body">  
  8.                       <div>  
  9.                           <button (click)="toggle()">Hide/Show Child </button>  
  10.                           <app-second *ngIf="displayChild"></app-second>  
  11.                       </div>  
  12.                     </div>  
  13.                   </div>  
  14.                 </div>  
  15.               </div>`,  
  16.   styleUrls: ['./app.component.css']  
  17. })  

And put the below code inside the class

  1. export class AppComponent {  
  2.   displayChild = true;  
  3.   constructor() {  
  4.       console.log('AppComponent:Constructor');  
  5.   }  
  6.   toggle() {  
  7.       this.displayChild = !this.displayChild;  
  8.   }  
  9.   ngOnInit() {  
  10.       console.log('AppComponent:OnInit');  
  11.   }  
  12.   ngOnDestroy() {  
  13.       console.log('AppComponent:OnDestroy');  
  14.   }  
  15. }  

See the below output:


In the above picture, when child component is projected into our parent’s component then as per our above code, first constructor of Parent’s component runs, after that ngOnInit() of Parent’s component runs, after that ngOnInit() of child’s component. We can see messages on console screen.

Now, the question is, how am I sure about that my child’s component can be projected into Parent’s component?

So, the answer is, press F12 for developer tool, go to the elements and see template of Second component (“<app-second>”) which is our child component that can be attached with DOM (look into picture).

Now, if we click on Hide/Show button, then it destroys the component or we can say detaches the component from parents component. But before the destruction it executes ngOnDestroy() hook and displays the message on the console screen and after that we are also not seeing “<app-second>” into elements tab inside the developer’s tools. Please look at the below picture

This is all about the Component’s life cycle hook with example. Now, at the end of the article I want to draw your attention that this cycle hook is changed a little bit when child’s component is created. Please have a look at the  below picture



As we know, components are very important in Angular and as a developer, we should know about these hooks also. After reading this article, we can say that we have knowledge of life cycle hooks and what is the role of those hooks in Angular projects.

I attached a demo sample application “SampleLifeCycleHook” in my previous lifecycle hook i.e. on “Angular 5 – Lifecycle Hook”, this project contains the code related to all lifecycle hooks.


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now