Component Lifecycle Hooks in Angular 2

Posted By : Milind Ahuja | 29-Jan-2018

Each Angular application has a lifecycle. Angular 2 is components based, so each component goes through its own lifecycle. As you already know that each component has it's own constructor and it's relevant to know that the way to access the inputs of a component is not via it's constructor.

In order to access the value of the input, let us take an example of loading the data from ther server, you have to use a lifecycle phase.

Following phases are available:

Constructor:

The constructor of the component class is called before any other component lifecycle hook. If there are any dependencies in our component, the best place to inject them is the constructor.

Example:

import {Component} from 'angular2/core';
import {ProductService} from './productService';
@Component({
  selector: ‘list-products’,
  template: `
    
  • {{product.name}}
` }) class AppComponent { products:Array; constructor(private productService: ProductService) { this.products = _productService.getProducts(); } }

ngOnInit:

This is place where initialisation work should be done because ngOnInit method is called directly after the constructor and after the ngOnChange is triggered for the first time.

ngOnChanges:

When the value of a bound property changes, this will be called first. This will be executed, every time the value of an input changes.

ngOnChanges:

When the value of a bound property changes, this will be called first. This will be executed, every time the value of an input changes.

{"brand":{"previousValue":"","currentValue":"BMW"}}

In the above example, one change in the input will be reported. The value of this property is changed from an empty string to "BMW".

ngOnDestroy:

This is called when the component is about to destroy and this is the perfect place for component cleaning.

@Directive({
    selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {
  sayHello: number;
  constructor() {
    this.sayHiya = window.setInterval(() => console.log('hello'),     1000);
  }
  ngOnDestroy() {
     window.clearInterval(this.sayHiya);
  }
}

In the above example, without using ngOnDestroy method, we will have the thread printing "hello" until the end or crashes.

Each of these mentioned hooks can be useful for executing methods during specific events triggered by a component during its instantiation, updation and existence. Attaching a lifecycle hook is pretty simple and only requires 3 steps:

// 1. Import our lifecycle hook
import {OnInit, OnDestroy} from '@angular/core';

@Directive({selector: '[myDirective]'})
export class MyDirective implements OnInit, OnDestroy {
// 2. Declare the interface on our class above

  constructor() { }

// 3. Implement the lifecycle hooks

  ngOnInit() { console.log('onInit'); }

  ngOnDestroy() { console.log('onDestroy'); }
}

To go deeper in the details, you can have a look at the following documentation created by the Angular Team :

https://angular.io/guide/lifecycle-hooks#!#other-lifecycle-hooks

THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..