in Angular by
What are lifecycle hooks in Angular? Explain a few lifecycle hooks.

1 Answer

0 votes
by

Every component in Angular has a lifecycle, different phases it goes through from the time of creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger changes at specific phases in a lifecycle.

ngOnChanges( ) This hook/method is called before ngOnInit and whenever one or more input properties of the component changes.

This method/hook receives a SimpleChanges object which contains the previous and current values of the property.

ngOnInit( ) This hook gets called once, after the ngOnChanges hook.

It initializes the component and sets the input properties of the component.

ngDoCheck( ) It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular.

We can implement our change detection algorithm in this hook. ngAfterContentInit( ) It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.

ngAfterContentChecked( ) It gets called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.

ngAfterViewInit( ) It responds after a component's view, or a child component's view is initialized.

ngAfterViewChecked( ) It gets called after ngAfterViewInit, and it responds after the component's view, or the child component's view is checked.

ngOnDestroy( ) It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.

Let’s understand how to use ngOnInit hook, since it’s the most oftenly used hook. If one has to process lot of data during component creation, it’s better to do it inside ngOnInit hook rather than the constructor:

    

      import { Component, OnInit } from '@angular/core';

      @Component({

        selector: 'app-test',

        templateUrl: './test.component.html',

        styleUrls: ['./test.component.css']

      })

      export class TestComponent implements OnInit {

        constructor() { }

        ngOnInit() {

          this.processData();

        }

        processData(){

          // Do something..

        }

      }

    

  

As you can see we have imported OnInit but we have used ngOnInit function. This principle should be used with the rest of the hooks as well.

...