Angular Lifecycle Hooks

Table of contents
Reading Time: 4 minutes

Every Angular component has a lifecycle. A component has a lifecycle managed by Angular itself. Angular manages creation, rendering, data-bound properties, etc. Every Angular component and Angular directive have a lifecycle and the following information can be applied to both. In this blog, we will learn more about Angular Lifecycle Hooks.


What is Angular Lifecycle?

Each Angularjs version goes through various phases in its lifecycle. It also offers hooks that allow us to respond to key lifecycle events.
Component creates anytime
-Create the component
– renders the component
– creates and renders the component children
– Check when the component data-bound properties change
– Destroys the component before removing it from the DOM.
Angular offers “lifecycle hooks” that provide visibility into these key life moments and the ability to act when they occur. A directive has the same set of “lifecycle hooks”. For the smoothness in the development process, Angular manages all its components. That is a very simple description of the sequence of events that an Angular component’s life experiences. These events are called “Lifecycle Hooks”.


There are eight different lifecycle hooks that a developer can tap into in any component or directive.

  • ngOnChanges – called when an input binding value changes
  • ngOnInit – after the first ngOnChanges
  • ngDoCheck – after every run of change detection
  • ngAfterContentInit – after component content initialized
  • ngAfterContentInitChecked – after every check of component content
  • ngAfterViewInitChecked – after component’s view(s) are initialized
  • ngAfterViewInit – after every check of a component’s view(s)
  • ngOnDestroy – just before the component is destroyed

The order in which these lifecycle hooks are specified of each the order they executes. In all these hooks, the most common hooks are used.
ngOnChanges, ngOnInit, and ngOnDestroy.

So lets see these commonly use angular life cycle hooks.

ngOnChanges: This event gets executed as and when the input control gets renewed inside the component. This is called before “ngOnInit”. This life cycle hook executes every time the value of input property changes.
Key:

  • Used in pretty much any component that has an input.
  • Called whenever an input value changes
  • Is called the first time before ngOnInit

ngOnInit: This event gets its call only after ngOnChanges event and after the constructor. Executes after the constructor and after ngOnChange hook for the first time. It is most commonly used for component initialization and retrieving data from a database.
Key:

  • Used to initialize data in a component.
  • Called after input values are set when a component is initialized.
  • Added to every component by default by the Angular CLI.
  • Called only once

ngDoCheck:This hook comes on demand instantly after ngOnInit, and this hook has its duty of execution even if there is no change in the property of a component.
Key:

  • Called during all change detection runs
  • A run through the view by Angular to update/detect changes

ngAfterContentInit:“ngAfterContentInit” becomes a demand next to ngDoCheck when every content of the components gets introduced and checked for the first time.
Key:

  • Called only once after first ngDoCheck()
  • Called after the first run through of initializing content

ngAfterContentChecked:This hook method accomplishes its work by investigating the modification in the content of the component using Angular change detection apparatus, and it still performs its task even if there is not at all any modification. It gets its call after ngAftercontentInit and also gets executed after every execution od ngDoCheck.
Key:

  • Called after every ngDoCheck()
  • Waits till after ngAfterContentInit() on first run through

ngAfterViewInit:This lifecycle method gets its call after ngAfterContentChecked and finds its use only on components. It gets invoked only after all the component view and its child view. This is very much similar to ngAfterContentInit.
Key:

  • Called after Angular initializes component and child component content.
  • Called only once after view is initialized

ngAfterViewChecked:This method gets its call after ngAfterViewInit and then for every ngAfterContentChecked method. This Angular lifecycle method gets triggered subsequently as it checks component’s view and child view.
Key:

  • Called after all the content is initialized and checked. (Component and child components).
  • First call is after ngAfterViewInit()
  • Called after every ngAfterContentChecked() call is completed

ngOnDestroy:This lifecycle hook executes just before angular destroys the component and generally used for performing cleanup. This is the place where you can use your clean up logic and unsubscribe from all observable and detach from event handlers, by doing so you can prevent memory leakage.
Key:

  • Used to clean up any necessary code when a component is removed from the DOM.
  • Fairly often used to unsubscribe from things like services.
  • Called only once just before component is removed from the DOM.

Angular Lifecycle Hooks

3 simple steps to use the life cycle hooks

Step1: Import the life cycle hook interface.
import { OnInit } from ‘@angular/core’;
to use ngOnInit() life cycle hook, import OnInit interface.

Step2: Make the component class implement the life Cycle Hook interface,
export class SimpleComponent implements OnInit
using the “implements” keyword as shown above. This step is optional, but good to have so you will get editor support and flags errors at compile time if you incorrectly implement the interface method or make any typographical errors.

Step3: Write the implementation code for the life cycle interface method.
ngOnInit(){ console.log(‘OnInit life cycle Hook’); }
Each interface has a single hook method whose name is the interface name prefixed with ng.

Now we will go through the lifecycle hooks according to the sequence of their execution

For Example

export class LifecycleHooksComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log('ngOnInit');
}
ngOnChanges(){
console.log('ngOnChanges');
}
ngDoCheck(){
console.log('ngDoCheck');
}
ngAfterContentInit(){
console.log('ngAfterContentInit');
}
ngAfterContentChecked(){
console.log('ngAfterContentChecked')
}
ngAfterViewInit(){
console.log('ngAfterViewInit');
}
ngAfterViewChecked(){
console.log('ngAfterViewChecked');
}
ngOnDestroy(){
console.log('ngOnDestory');
}
}

Run the application and open browser developer tools ( Ctrl+Shift+I ). The changes will be visible in the console.

Angular Lifecycle Hook Console

Reference:
https://angular.io/guide/lifecycle-hooks
https://www.intertech.com/Blog/angular-component-lifecycle/
http://csharp-video-tutorials.blogspot.com/2017/08/angular-component-lifecycle-hooks.html
https://www.cuelogic.com/blog/angular-lifecycle

Knoldus-blog-footer-image