our

Latest Blogs

A Guide on Component Life Cycle Hooks in Angular

iFour Team -June 17, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  •  
  •  
  •  
A Guide on Component Life Cycle Hooks in Angular

What is Life Cycle hooks in Angular?

A component example has a life cycle that starts when the angular body of the component class and puts up the component view along with its child view. The life-cycle persistent with change detection, as angular audits to see when data-bound properties change, and updates both the component and the view example as required. The life cycle closes when angular destroys the component example and removes its rendered template from the Document object model.

Angular directives have the same life cycle, as angular is created, updated, and destroyed instances in the course of execution.

Responding to Events in the Life cycle

You can say something in response to an event in the life cycle of a component or directive by applying one or more of the life cycle look interfaces in the Angular core library.

The hooks give you the chance to act on a component or directive instance at a suitable moment as angular is created, update, and destroy that instance.

Each interface denotes the prototype for a single hook method, and the interfa ce name prefixed with ng. For example, the onChnge interface has a hook method named ngOnChanges().

@Directive({selector: '[appPeekABoo]'})
                export class PeekABooDirective implements OnChanges {
                  constructor(private logger: LoggerService) { }
                  // implement OnChnage's `ngOnChanges` method
                  ngOnChange() {
                    this.logIt(`OnChanges`);
                  }
                  logIt(msg: string) {
                    this.logger.log(`#${nextId++} ${msg}`);
                  }
                }

Life Cycle Events

Angular execute hook methods in the following order. You can use them to perform the following kind of operation.

ngOnChanges()

ngOnChanges() is the first hook of the life cycle.

It is called right after your class gets started to run and the component is created the ngOnChange() is called.

You might know why ngOnInit() hook is not called first, because angular count first class initialization as data property change. So the hook gets called first data property change that occurs is ngOnChange().

You can test out ngOnChange hook, so you can use the below code:

// src/app/app.component.ts
                  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 = 'canvas';
                  constructor(){
                  alert("on changes is called");
                  }
                  }

This code writes in the app.component.ts file.

When you run the application, the alert will pop up display before the component will be loaded.

ngOnInit()

ngOnInit() is the second life cycle hook in angular. It is called right after the ngOnChanges() hook is called.

ngOnInit() is initialize the component, and sets and displays component input properties.

ngOnInit() is most important hook in the angular life cycle hook, and it is called only once. So it is great for fetching data from external source like API and servers.

You can test out ngOnInit hook, so you can use below code:

// src/app/app.component.ts
                    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("second on init is called");
                    }
                    ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
                    }
                    title = 'ngcanvas';
                    constructor(){
                    alert("first on changes called");
                    }
                    }

ngDoCheck()

ngDoCheck() is third hook of angular life cycle. ngDoCheck() is called during each change detection run, angular has an internal system that goes around the component process each so often looking for changes that the compile cannot detect on its own.

ngDoCheck() hook is called each change detection run, after the onInit() hook is called.

You can test out ngDoCheck() hook, so you can use below code:

ngAfterContentInit()

ngAfterContentInit() is four hook of angular hook cycle, and its calls after a component has been initialized.

ngAfterContentInit() hook is only once ngDoCheck() hook is called, it is one type of ngDoCheck() but ngAfterContentInit() hook content projected into the component view with ng-content.

You can test out ngAfterContentInit() hook, so you can use below code:

// src/app/app.component.ts
                      import { Component, OnChanges, OnInit, DoCheck } from '@angular/core';
                      @Component({
                      selector: 'app-root',
                      templateUrl: './app.component.html',
                      styleUrls: ['./app.component.css']
                      })
                      export class AppComponent implements OnChanges, OnInit, DoCheck {
                      ngDoCheck(): void {
                      alert("Third do check is called");
                      }
                      ngOnInit(): void {
                      alert("Second on init is called");
                      }
                      ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
                      }
                      title = 'ngcanvas';
                      constructor(){
                      alert("First on changes is called");
                      }
                      }

ngAfterContentChecked():

ngAfterContentChecked() hook the fifth hook of the angular lifecycle, and it is called after a component has been initialized.

This hook is called after the ngAfterContentInit() hook and each subsequent ngDoCheck() hook is called.

You can test ngAfterContentChecked() hook with use of previous example and archive create the alert for ngAfterViewInit() hook.

ngAfterViewInit():

ngAfterViewInit() is the sixth hook of the angular lifecycle, and it is called after a component has been initialized.

This hook is called after the ngAfterContentChecked() hook.

This hook is after initializes component views and subsequent child view under every component, and this will have to include the views displayed content projection too.

You can test the ngAfterViewInit() hook with the use of the previous example and archive create the alert for ngAfterViewInit() hook.

One-stop-oplossing voor Angular-webontwikkeling Uw zoekopdracht eindigt hier.

ngAfterViewChecked():

ngAfterViewChecked() is the seventh hook of the angular lifecycle, and it is called after a component has been initialized.

This hook called after ngAfterViewInit() hook and each subsequent of ngAfterViewInit() hook.

ngOnDestroy()

ngOnDestroy() is the last hook of the angular life cycle, and it is called before the component is removed from the DOM.

This hook is follow previous hook pattern and archive create the alter for this.

Now, we use the all hooks of the angular life cycle hooks:

// src/app/app.component.ts
  import { Component, OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy } from '@angular/core';
  @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnChanges, OnInit,
  DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit,
  AfterViewChecked, OnDestroy{
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
  }
  ngOnInit(): void {
  alert("Second on init is called");
  }
  ngDoCheck(): void {
  alert("Third do check is called");
  }
  ngAfterContentInit(): void {
  alert("Fourth after content init called");
  }
  ngAfterContentChecked(): void {
  alert("Fifth after content check called");
  }
  ngAfterViewInit(): void {
  alert('Sixth after view init called');
  }
  ngAfterViewChecked(): void {
  alert('Seventh after view init checked');
  }
  ngOnDestroy(): void {
  alert('Last on destroy hook is called');
  }
  title = 'ngcanvas';
  constructor(){
  alert("First on changes is called");
  }
Conclusion

In this blog, we have seen various life cycle hooks of Angular and how to implement in the Angular application. Now you know the reason behind the hooks you always used in your workflow.

Work with us

Well do everything we can to make our next best project!

Our Insights

Check out our most recent blogs

An in-depth guide on Angular Dependency Providers
An in-depth guide on Angular Dependency Providers

What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...

A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe
A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe

Angular Templates seamlessly help to expedite the development process with flawless assistance of components and other specific elements. These are dynamic and renders according...

A simple guide on AOT Compilation in Angular
A simple guide on AOT Compilation in Angular

What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...

Our Partners

Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo

Work With Us

Well do everything we can to make our next best project!