Angular Component Lifecycle Hooks.

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.

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.

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.

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

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(``); 
}
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.

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…