Browse Articles

Angular Component Lifecycle Hooks Explained

 Print   8 min read  
23 Jul 2022
Advanced
21K Views

We have worked with Components and Directives in Angular quite a lot now. And if dear Reader, you are new to Components or directives, refer here. When dealing with components or directives, there is a sequence of steps that are performed to build an angular application. These steps range from the process of its initialization to its destruction. This whole process of the component or the directive is known to be its LifeCycle.

An important aspect of the Angular lifecycle hooks is their order or the sequence of the execution. It never deviates and they can be executed based on a predictable series of load events produced from a detection cycle and trigger the desired action based on the business requirements such as doing network calls, updating variables, managing global state objects, etc.

Angular lifecycle hooks are listed below in the given diagram.

Angular Lifecycle hooks diagram

The lifecycle of a component/directive is managed by Angular as it creates, checks, updates, renders, and destroys. To have a view of all these occurrences and respond to these moments, Angular provides lifecycle hooks that give us visibility into these. These lifecycle hooks can be implemented by the interfaces provided in the Angular Core Library. This is the same with components and directives. Every interface contains different lifecycle hook methods, named with the interface name prefixed with ng. Like the very commonly used lifecycle hook ngOnInit() is named as ng(prefix) and OnInit (interface name).

The framework Angular offers various lifecycle hooks which provide visibility into these key life moments and the ability to act when they occur during the complete compilation life cycle.

Constructor

Whenever working with components, the first step is the calling of the constructor. This happens even before the implementation of any lifecycle hook. Also, if our component has any dependencies, a constructor is where we can inject those.

At this point till the constructor, none of the component's input properties are available to use in the template or in the component itself. Neither its child components are constructed. Nearly all the projected contents are also available for the manipulations. 

A simple example of the usage of the constructor would be as:

import {Component} from 'angular2/core';
import {ValService} from './valService';

@Component({
 selector: ‘app-root’,
 template: `
 `
})
class AppComponent {
 value: String;
 constructor(private _valService: ValService) {
 this.value = _valService.getValue();
 }
}

About the Lifecycle Hook methods

ngOnChanges()

A lifecycle hook method is called when any of the properties bound already have their value changed. This method is called every time there comes a change in the value. The method gets an object SimpleChanges of the previous and current value of the property.

In other words, the lifecycle hook ngOnChanges() is Invoked every time whenever there is a change in one of the input properties of the component.

An example goes like this:

ngOnChanges(changedvals: SimpleChanges) {
 for (let f in changedvals) {
 let c = changedvals[propName];
 let current = JSON.stringify(c.currentValue);
 let previous = JSON.stringify(c.previousValue);
 this.changeLog.push(`${propName}: currentValue = ${current}, previousValue = ${previous}`);
 }
}

ngOnInit()

The method is called right after the constructor and the ngOnChanges() method are triggered. This is the lifecycle hook used for the initialization of the component/directive. One important thing to notice here is that ngOnChanges() always executes before ngOnInit().

The ngOnInit() hook is the most important lifecycle hook in Angular because it identifies the initialization of the newly created component. The fact that this hook is called only once during the rendering, Most importantly, this hook is being used for fetching data from external sources like servers and APIs.

ngOnInit() 
 {
 this.logIt(``); 
 }

ngDoCheck()

Angular does not detect changes by itself so for that, we need another lifecycle hook called ngDoCheck(). This is run every time after ngOnInit() and ngOnChanges() and is executed every time the process of change detection takes place.

The hook ngDoCheck() allow the developers to check their data manually. It can be used to trigger a new application date conditionally. In conjunction with "ChangeDetectorRef", the developers can create their own checks for change detection.

ngDoCheck() {

 if (this.val !== this.oldval) {
 this.changeDetected = true;
 this.changeLog.push(`DoCheck: Value changed to "${this.val}" from "${this.oldval}"`);
 this.oldval = this.val;
 }

 this.changeDetected = false;
}

ngAfterContentInit()

This lifecycle hook is invoked whenever there is content projection happening inside the component’s view. This one is invoked just once after ngDoCheck() and once all the bindings of the components have been checked.

This lifecycle hook is called only once during the component’s lifecycle execution and after the first ngDoCheck() hook. And by using this hook, we have all the access for the first time for accessing the "ElementRef" of the "ContentChild()" after the component’s creation; along with the projected external content into the component’s view seamlessly.

ngAfterContentChecked()

Invoked right after ngAfterContentInit() and subsequent ngDoCheck(), this lifecycle hook responds after the content of the component has been checked by the content projection process. This hook method is always called in response.

@ContentChild(ChildComponent) contentChild: ChildComponent;

 ngAfterContentInit() {

 this.logIt('');
 }

 ngAfterContentChecked() {

 if (this.val === this.contentChild.val) {
 this.logIt('Checked with no change');
 } 
 else {
 this.val = this.contentChild.val;
 this.logIt('Checked');

 }
 }

ngAfterViewInit()

This one is invoked after all the component bindings have been checked with the use of ngAfterContentInit() and ngAfterContentChecked(). This is also a response hook method that invokes when component views and child views are initialized by Angular. And this applies only to components and not directives.

Angular ngAfterViewInit() hook is a method of the "AfterViewInit" interface and the ngAfterViewInit() is a lifecycle hook that is called after the Angular component's view has been completely initialized. ngAfterViewInit() is used to handle any additional initialization tasks as or whenever required.

ngAfterViewChecked()

A response hook method is invoked every time Angular has checked the component views and the child view. It takes place even if there has been no change or update. This also applies only to components. This is invoked right after ngAfterViewInit() and every subsequent ngAfterContentChecked().

export class AfterViewComponent implements AfterViewChecked, AfterViewInit {
 private val = '';

 @ViewChild(ChildComponent) viewChild: ChildComponent;

 ngAfterViewInit() {

 this.logIt('');
 }

 ngAfterViewChecked() {

 if (this.val === this.viewChild.val) {
 this.logIt('AfterViewChecked ');
 } else {
 this.val = this.viewChild.val;
 this.logIt('AfterViewChecked');
 }
 }

ngOnDestroy()

When a component comes to its last stage, Angular has the task of destroying it. So before the destruction of the component/directive, some important detachment steps have to take place. These steps are performed by our ngOnDestroy() lifecycle hook method.

In other words, The hook "ngOnDestroy()" gets fired when any of the application components are going to be removed from the view and subsequent DOM structure. This hook provides the feasibility to clean up any unattended ends before a component’s deletion from the DOM.

This method is implemented right before Angular destroys the component/directive. Some of the processes that this method performs are :

  • Clean Up

  • Unsubscribe Observables

  • Detach Event Handlers to avoid memory leak

  • Stop Interval timers

  • Unregister Callbacks

ngOnDestroy()
{
 this.logIt(``); 
}
The feasible behavior is for the ngDoCheck, ngAfterContentChecked and ngAfterViewChecked hooks to be called multiple times as soon as any changes occur so that the multiple occurrences of the event may not affect web application performance.
Summary

Angular applications use various types of lifecycle hook methods to tap into key events in the lifecycle of a component or the directive to initialize new instances as or whenever required, initiate the change detection strategy when needed, respond to the updates during any type of change detection, and finally to do the deep clean up before the deletion of the certain instances.

In this article, we discussed what is a component lifecycle and how to respond to the process in the working of components, it uses lifecycle hook methods. We also saw the demonstration of each of the lifecycle hooks in the order of how they are invoked in working with components and directives, components specifically. From the initialization to the destruction of the component, the Angular online training program helps you learn to build projects using web API ASP.NET  MVC5  and node.js. this article covered all the hook methods required.

| Read More: Angular Interview Question and Answer

Learn to Crack Your Technical Interview

Accept cookies & close this