How to use Angular Lifecycle hooks

A component has a lifecycle which is managed by Angular. Below are the Angular component life cycle hooks:

  1. Create
  2. Render
  3. Create/Render child components
  4. Process Changes
  5. Destroy

Angular creates the component then renders it. After that it get the creates and renders its child components. If there are any changes in component’s data bound properties then processes changes and at last destroys it before removing its template from the DOM.

Angular provides a set of lifecycle hooks and below are few of them:

  1. OnInit – it is used to perform component initialization and it is used to perform any component initialization after Angular has initialized the data bound properties. It is a good place to retrieve the data for the template from a back-end service.
  2. OnChanges - It is used to perform any action after Angular sets data bound input properties.
  3. OnDestroy – This lifecycle hook to perform any clean-up before Angular destroys the component.

Using Angular Lifecycle Hooks

To use a lifecycle hook, you have to follow the below steps:

Implement the lifecycle hook interface

Angular provides several interfaces you can implement, including one interface for each lifecycle hook. For example, the interface for the OnInit lifecycle hook is OnInit.

export ProductListComponent implements OnInit {
Import Lifecycle hook from Angular packages

You have to import the lifecycle hook interface. Include OnInit in the import statement with Component as below

import { Component, OnInit } from '@angular/core';
Implement lifecycle hook method

After that you have to implement lifecycle hook method. Lifecycle hook interface defines one method which has name prefixed with ng with interface name. For example, the OnInit interface hook method is named ngOnInit.

ngOnInit() { // Some code here } 

Complete component declaration:

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

@Component({
  selector: 'pm-products',
  templateUrl: './product-list.component.html',
  styleUrls:['./product-list.component.css']
})
export class ProductListComponent implements
{
       constructor() { }
      ngOnInit() { }
}

In this you can use another Angular Lifecycle hooks to implement required functionality at particular event.