Lifecycle Hooks In Angular

Lifecycle hooks in angular are a very important concept which you must know. You will definitely use lifecycle hooks in angular very often. Once the component in angular is instantiated, angular go through some phases in the component creation process. We can hook through these phases and put some code in them. We can hook through these phases through some methods that angular offers. These methods are called lifecycle hooks in angular.

You will learn the following topics about lifecycle hooks in angular.

  1. Objectives
  2. Lifecycle hooks in angular
  3. Execution order of lifecycle hooks in angular
  4. Using lifecycle hooks example
  5. Lifecycle hooks interfaces
  6. Summary

Objectives:

You will learn the following objectives from this article.

  • Different lifecycle hooks angular uses from process of component creation to component destruction.
  • You will learn to use these lifecycle hooks to implement your own code.
  • You will learn the order in which lifecycle hooks gets executed.
  • Different use of these lifecycle hooks.

Lifecycle hooks in angular:

Following are the lifecycle hooks in order of execution that angular offers.

1) ngOnChanges:

This lifecycle hook can get called multiple times. It is called at the start when the component is created. Also, it is called when any input property which is bound to component changes. This means if you have used @Input decorator in your component and the value of this input property is changed then ngOnChanges lifecycle hook gets called.

2) ngOnInit:

This lifecycle hook gets executed once the component is instantiated. You can access and initialize properties using the ngOnInit lifecycle hook. You can also call functions that you want to execute once the component is instantiated. ngOnInit lifecycle gets executed after the constructor is created.

3) ngDoCheck:

This lifecycle hook gets called multiple times when change detection is run. Change detection is a mechanism by which angular determines whether something is changed in a component like values of properties that needs to be changed on template. ngDoCheck gets executed each time change detection is run. template of the component gets re-rendered when ngDoCheck gets called. ngDoCheck gets executed each time something is changed or each time user makes some changes on UI. You can use the ngDoCheck lifecycle hook to inform angular about some changes that should be detected which angular is not being able to detect by default.

4) ngAfterContentInit:

This lifecycle hook is executed once content shown using ng-content has been initialized. This hook gets called when angular inserts external content into components view or into a view that directive is in.

5) ngAfterContentChecked:

This lifecycle hook gets called when change detection detects the external projected content from the component.

6) ngAfterViewInit:

This lifecycle hook gets called once the view of the component gets initialized. So, ngAfterViewInit gets called after the component view is rendered.

7) ngAfterViewChecked:

This lifecycle hook gets executed once the view of the component is checked by change detection and displayed all the changes on view.

8) ngOnDestroy:

This lifecycle hook is executed once the component is destroyed. This lifecycle is used to implement code related to clean-up work.

Execution order of lifecycle hooks in angular:

Lifecycle hooks in angular get executed in the below order.

Lifecycle Hooks Execution Order

Using lifecycle hooks:

You will learn about how to use lifecycle hooks in this section. Follow the below steps to learn how to use lifecycle hooks in angular.

1) Create a new angular application:

Create a new angular application using the following command:

ng new lifecycle-hooks

Here, lifecycle-hooks is the project name.

2) Create a new component:

Create a new user component by the following command to implement lifecycle hooks in it.

ng g c user

3) Put the following code in the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users = ['John', 'Jane', 'Tom'];

  addUser() {
    this.users.push('Steve');
  }
}

3) Put the following code in the app.component.html file.

<h1>Lifecycle hooks in angular.</h1>
<app-users [users]='users'></app-users>
<br>
<button (click)="addUser()">Add User</button>

4) Put the following code in the user.component.ts file.

import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, 
  AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {

  @Input('users') users;
  constructor() {
    console.log('constructor called.');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called.');
    console.log(changes);
  }

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

  ngDoCheck() {
    console.log('ngDoCheck called.');
  }

  ngAfterContentInit() {
    console.log('ngAfterContentInit called.');
  }

  ngAfterContentChecked() {
    console.log('ngAfterContentChecked called.');
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit called.');
  }

  ngAfterViewChecked() {
    console.log('ngAfterViewChecked called');
  }

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

5) Put the following code in the user.component.html file.

<h4>Users: </h4>
<div *ngFor="let user of users">
  {{user}}
</div>

6) Run your project:

After completing all of the steps above, run your project using the ng serve command and open your application in the browser. After that open dev tools from the browser. And open the console tab from dev tools. You will see the following output. From the output, you will see different logs that are added in UsersComponent lifecycle hooks.

Execution of lifecycle hooks in angular

Note:
Here, you will not see the log of the ngOnDestroy lifecycle hook getting executed. That’s because we are not destroying UsersComponent here. But if you are using routing in your application, and you navigate from one page to another, then UsersComponent will get destroyed and you will see the log from the ngOnDestroy lifecycle hook method.

You can see also see the logs of changes from the ngOnChanges lifecycle hook. These changes are of input property which is receiving its value from AppComponent. If you click on the ‘Add User’ button from UI, you will see some lifecycle hooks will get executed again. This hook gets executed after change detection from angular. You will see the following lifecycle hooks getting executed after clicking on the ‘Add User’ button.

Execution of lifecycle hooks after change detection

Lifecycle hooks interfaces:

You can directly use lifecycle hooks in your component. But, you can explicitly import and add interfaces to the class of your component so that we can expect those hooks to be implemented in our component. You can add interfaces of lifecycle hooks from ‘@angular/core’. If you mention a particular interface to your class and didn’t add that lifecycle hook method in the component then TypeScript throws an error. All lifecycle hooks have interfaces with the same name without ng prefix. In the above demo of using lifecycle hooks, interfaces of lifecycle hooks are implemented.

You can use interfaces of lifecycle hooks like the following:

import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, DoCheck, Input, OnChanges, OnDestroy,
         OnInit, SimpleChanges } from '@angular/core';

export class UsersComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, 
  AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy { 
    // Your Code of UsersComponent 
}

Summary:

Lifecycle hooks in angular are used during component creation, updating, and destruction. Mostly ngOnInit, ngOnChanges, ngOnDestroy, and ngAfterViewInit lifecycle hooks are used in projects.
If you have any questions related to this article, you can ask them from the comment section below.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments