Life Cycle hook of Angular 2 Component

I
n my previous post, I have explained about Angular 2 Components in detail. Why do we need component and what it is exactly? 

Now let us understand more about component lifecycle hook and look at some of the code explaining about component life cycle in detail. Let's get started.

A component lifecycle is managed by angular itself. Component life cycle comprises of following stages:

  1. Create
  2. Render
  3. Create and render children
  4. Process changes
  5. Destroy

 

Please refer the diagram shown below:

 

Component life cycle

 

 

Let me explain you with an example in angular 1.x how we can take advantage of a life cycle of the component.

If you remember in Angular 1.x we use ngCloak to hide {{}} interpolation before data renders. But now in Angular 2.x we have lifecycle where we can easily manage it.

Now let us understand the component life cycle in detail. But before that let me explain about constructors in the component as it is an important part before diving into the life cycle.

Component Constructor

Every component ha a constructor. Refer example shown below:

import { Component } from '@angular/core'
import { TextService } from './service/TextService'

@Component({
    selector: 'my-products',
    templateURL: 'app/products/product-list.component.html'
})

export class ProductListComponent { 
        text: string;
        constructor (private text: TextService) {
           this.text = TextService.getText();
        }
}

Please make a note that constructor of the component is called before any other component lifecycle hook. The constructor is also placed to inject dependency if our component has any. 

For example, Our ProductListComponent is dependent on TextService. So we need to import a service and inject in the constructor. This is how dependency injection works in Angular 2.x.

Now, we know about constructors so let's move forward and understand about component lifecycle.

Component basically has four stages. These are:

  1. ngOnInit
  2. ngOnChanges
  3. ngOnDestroy
  4. ngDoCheck

Each interface has a single hook method whose name is the interface name prefixed with ng. For example, the `OnInit` interface has a hook method named `ngOnInit()`.

Let see each stage in detail:

ngOnInit

This is the stage which gets executed once the component is initialized. This hook is only called once. Refer the code below to see how exactly hooks are implemented.

import { Component } from '@angular/core'
import { TextService } from './service/TextService'
import { OnInit } from '@angular/core'

@Component({
    selector: 'my-products',
    templateURL: 'app/products/product-list.component.html'
})

export class ProductListComponent implements OnInit{ 
        text: string;
        constructor (private text: TextService) {
           this.text = TextService.getText();
        }
        ngOnInit() { console.log('Component Initialized'); }
}

As you can see in above code we first need to implement an interface which is OnInit in above case. Then we have a function ngOnInit() which will get executed once our component is initialized.

Also, note that ngOnInit is better place to initialize component then constructor because at ngOnInit is the stage where all input properties are initialized.

ngOnChanges

This is a hook which is invoked every time when there is a change in input properties.

import { Component } from '@angular/core'
import { TextService } from './service/TextService'
import { OnChanges } from '@angular/core'

@Component({
    selector: 'my-products',
    templateURL: 'app/products/product-list.component.html'
})

export class ProductListComponent implements OnChanges{ 
        text: string;
        @Input() name: string;

        constructor (private text: TextService) {
           this.text = TextService.getText();
        }
        ngOnChanges( changes: productChanges) {
             if(changes) { this.text = 'Value changed' }
        }
}

ngOnDestroy

This is a hook just before Angular destroys the component. This is best place to do all clean up activities like detaching of event handler to avoid memory leakage.

import { Component } from '@angular/core'
import { TextService } from './service/TextService'
import { OnInit, OnDestroy } from '@angular/core'

@Component({
    selector: 'my-products',
    templateURL: 'app/products/product-list.component.html'
})

export class ProductListComponent implements OnInit, OnDestroy { 
        text: string;
        constructor (private text: TextService) {
           this.text = TextService.getText();
        }
        ngOnInit() { console.log('Component Initialized'); }

        ngOnDestroy() { console.log('Component is destroyed'); }
}

ngDoCheck

This is invoked when OnChanges is invoked. This is provided by Angular to write our detection algorithm. We mostly write change detections that angular doesn't detect on its own.

Please make a note that it ngOnChanges and ngDoCheck should be implemented together in a component. 

Below are the children hooks of ngDoCheck and are only specific to components. Refer to link to know more about below hooks.

  1. ngAfterContentInit
  2. ngAfterContentChecked
  3. ngAfterViewInit
  4. ngAfterViewChecked

So to summarise,

Using component life cycle we can easily change our component behavior on initializing, updating and destroying. And based on usability in the code we will be mostly using ngOnInit because it is more preferred than the constructor, followed by ngOnChange and then ngOnDestroy.  Apart from these three, you will hardly need to use other component lifecycle hooks.

Author Info

Tavish Aggarwal

Website: http://tavishaggarwal.com

Tavish Aggarwal is a front-end Developer working in a Hyderabad. He is very passionate about technology and loves to work in a team.

Category