Angular Component Lifecycle Hooks Explained

Nishu Goel  Print 
20 Nov 2018
 
Intermediate
372

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. 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 which 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 both. 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).

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.

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

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 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.

An example goes like :

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 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().

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.

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 when ever there is content projection happened inside the component’s view. This one is invoked just once after ngDoCheck() and once all the bindings of the components have been checked.

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 which invokes when component views and child views are initialized by Angular. And this applies only to components and not directives.

ngAfterViewChecked()

A response hook method which 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 updation. 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 this 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.

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 so as to avoid memory leak

  • Stop Interval timers

  • Unregister Callbacks

ngOnDestroy()
{
 this.logIt(``); 
}
Summary

In this article, we discussed what is a component lifecycle and how to respond to the processed in the working of components, it uses lifecycle hook methods. We also saw the demonstration of each of the lifecycle hook in the order of how they are invoked in the working with components and directives, components specifically. From the initialization to the destruction of the component, this article covered all the hook methods required.

Crack Your Technical Interview

 
Join Our Hands-on Training Programs
+