Angular Component Lifecycle Hooks

Angular Component Lifecycle Hooks

In general, when we talk about the lifecycle of something, be it a component, function, or process, we technically mean the stages it has to undergo while coming into operation.

Now considering the above into account, with these aspects, every component in Angular goes through a process of creation, then for execution, it has to execute all the functions which it was initially created for and then accordingly go for possible destruction. To perform this cycle, Angular does it by creating a component, rendering it, and then creating and rendering all of its children. This process of rendering takes place in the Document Object Model (DOM), where Angular first checks for changes in the data properties, make appropriate updates, and when it is done finally, it destroys, and then it is removed from the DOM.

Lifecycle Hooks Explained

There are 8 stages of lifecycle hooks which a component goes through whenever it comes into operation. But why do we need these stages? Whenever we are working with an Angular application, there will be a lot of changes that will happen on the components. Let's consider some possibilities where the changes can be accounted for the component:

  • Some data might change when we do some operations.

  • We want some data to be loaded when the component is created.

  • When a component goes through some change, we want to make sure that some other component gets the latest information.

With these possibilities, Angular offers lifecycle hooks that can provide visibility into these stages and their ability to act when they occur. These 8 lifecycle hooks are described as below:

ngOnChanges()

This is the very first stage of lifecycle hooks and is called the first time before ngOnInit(). Whenever a class is initialized and the component is created, Angular counts this as a data property change and once this is done, ngOnChanges() gets called. This is also one reason why ngOnInit() doesn't get called first in the lifecycle hooks.

Example: Let's consider the app.component.ts file inside the app folder:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-login';
}

To test out ngOnChanges hook, we will have something as follows:

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
 })

export class AppComponent implements OnChanges {
    ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
}
    title = 'angular-login';
    constructor() {
    alert("1. on changes called");
    }
    }

We have brought the ngOnChanges hook from Angular and then initialized it with an alert statement in the constructor.

ngOnInit()

This is the second stage and is called right after the very first ngOnChanges hook is called. It is called only once, it initializes the component, sets, and displays component input properties. As it is called only once, this hook is great for fetching data from servers and APIs as external sources.

To test it out, let's add the ngOnInit hook syntax to the AppComponent class:

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })

export class AppComponent implements OnChanges, OnInit {
    ngOnInit(): void {
    alert("2. on init is called");
}

ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    }
    title = 'angular-login';

    constructor() {
       alert("1. on changes called");
 } 
}

When ngOnInit gets called, we will then be able to see alert pop-ups in the right sequence.

ngDoCheck()

This is the third hook and gets called on a component during every change detection run. It is an internal system in Angular which runs through the view to detect and update those changes which the compiler cannot detect on its own.

ngAfterContentInit()

This is the fourth hook and is called immediately after the first ngDoCheck is called and also after the first run-through of initializing content.

ngAfterContentChecked()

This is the fifth hook and is called by Angular after a component has been initialized. It is called after every subsequent ngDoCheck() and waits till after ngAfterContentInit() on first run through.

ngAfterViewInit()

This is the sixth hook and gets called only after the very first ngAfterContentChecked() is called as well as after Angular initializes component views and subsequent child component views. This is called only after one view gets initialized.

ngAfterViewChecked()

This is the seventh hook and is called after all the content related to component and child components is initialized and checked. This is immediately called after the very first ngAfterViewInit() as well as after every ngAfterContentChecked() call gets completed.

ngOnDestroy()

This is the last stage of the Angular lifecycle hook, which gets called just before the component is to be removed from the DOM. By doing this, ngOnDestroy() serves the purpose of cleaning up any necessary code and fairly often unsubscribe from things like services.

Some pointers to consider for Angular lifecycle hooks:

  • By default, we have ngOnInit()
  • Whichever lifecycle we want to use, we first have to import it in the class, extend the implements interface and then implement the method.

  • We can have any number of lifecycle hooks implementations.

Conclusion

To date, I have used ngOnInit() and ngOnChanges() and hence I was able to explain them in a bit more detail along with the code snippets. Using these 8 lifecycle hooks also depends on the project which we have to undertake and for me, my current project entails using these two. This also gave me a direction to know more about the lifecycle stages for Angular components.

For the code snippets of the remaining 6 stages, you can have a look at the reference links attached below this article, to get a practical understanding of the lifecycle hook stages.

Hope you found this article insightful!

Happy learning!

References: