Angular Component Lifecycle

Components are the main building blocks of any Angular application, each component goes through eight different stages of the lifecycle from initialization to destruction. Each stage is called a lifecycle hook event.

You can create the nested Angular components by visiting the Angular nested component. We will add each event code to the product and product-details component created by using this tutorial.

Component Lifecyle events

Every Angular component instance has a lifecycle that starts when Angular instantiates the component class. As component loads and unloads from DOM, every life cycle hook triggers sequentially that gives you an opportunity to do something for the component or its child component.

The lifecycle ends when Angular destroys the component and removes its rendered template from the DOM. These hooks are actually callback methods that Angular triggers when an event happens in the lifecycle of component.

You can execute hooks from the Angular Core library. @agnular/core is an Angular library that defines class infrastructure for components, view hierarchies, change detection, rendering, and event handling.

The following image shows the Angular lifecycle hooks execution sequence.

angular component life cyle hooks

The Angular component is TypeScript class, every component must have a constructor method. Angular will execute constructor first before any other lifecycle hook. Following is the detailed description of each hook in sequence.

  1. ngOnChanges

    This hook gets executed when any input control from the component sets or resets its value. This event fires first when a value of bound property has changed. It always receives a changed data map containing the present and previous value of the data-bound property wrapped in SimpleChange.

        {"ProductName":{"previousValue":"","currentValue":"Dell Laptop Inspiron"}}  
    

    In the above example, the value of ProductName has changed from an empty string to Dell Laptop Inspion.

    following is an implementation of ngOnChanges event. You will get all the changed properties of components in this hook. Open product-details.component.ts and replace following code for ngOnChanges event

    import { Component, OnInit, OnChanges, Input, Output, 
        EventEmitter, SimpleChanges } from '@angular/core';
    
    @Component({
      selector: 'app-product-details',
      templateUrl: './product-details.component.html',
      styleUrls: ['./product-details.component.css']
    })
    export class ProductDetailsComponent implements OnInit, OnChanges {
    
      constructor() { }
      
       ngOnChanges(changes: SimpleChanges) : void{  
            if(this.SalesRating == 3.5){  
                this._salesRating = 'Good';  
            } else if (this.SalesRating == 4.0){  
                this._salesRating = 'Very Good'  
            } else if(this.SalesRating == 4.5){  
                this._salesRating = 'Excellent'  
            } else {  
                this._salesRating = 'Undefined'  
        }
    
        for (const propName in changes) {
          const chng = changes[propName];
          const cur  = JSON.stringify(chng.currentValue);
          const prev = JSON.stringify(chng.previousValue);
          console.log(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
        }
     }
    }
    

    Verify the changes in developer tools -> console log.

    angular ngOnChanges hook

  2. ngOnInit

    This hook initialized Angular Component/Directive after Angular first displays the data bound properties properties or the component has been initialized which means this event will be called only once in life cycle of component after ngOnChanges event triggered.

    The best use of this event is to initialize data or fetch external data from services or API.

    Following is the code for initializing products-details component data. Open product-details.component.ts

      
      ngOnInit(): void {
        this._salesRating = 'Default';
        console.log("2. ngOnInit.");
      }
    
  3. ngDoCheck

    ngDoChek is an event that executes custom change-detection of component/directive, on top of the default Angular change-detector. It is called every change of component property after ngOnChanges and ngOnInit.

    This hook is most useful to detect and act upon the changes that can not be detected by Angular on its own.

    The child component's hooks are also checked when the parent component is being checked. There are three major operations happens when change detection is performed.

    • Update child component input bindings.
    • Update DOM interpolations.
    • Update Query List.

    In the case of Product(parent component) and Product-details(child component) implemented, following sequence of change detection will occur.

    • Checking Product Component

      1. Update product-details component input binding.
      2. Call ngDoCheck on product-details component.
      3. update DOM interpoation of product component.
      4. update DOM interpoation of product-details component.

    Add following ngDoCheck hook in products.component.ts file.

     ngDoCheck(): void {
      console.log("3. do check is called from parent.");
     }
    

    Add following ngDoCheck hook in products.component.ts file.

    ngDoCheck(): void {
        console.log("3. do check is called from child component.");
      }
    

    Result will be like this when you first Run your application.

    Angular ngDoCheck hook

  4. ngAfterContentInit

    This is the fourth lifecycle hook that gets triggered by Angular after the component has been initialized. It is called only once in life cycle immediately after the first ngDoCheck hook is called.

    This is called in response when Angular expects external contents into the component like use of ng-content. So it is not the view of the component itself but the other component may be parent component. External contents mean a way to import HTML content from outside the component and insert that HTML template or content to the component's HTML.'

    The best use of this hook is when component required something after all content has been initialized.

    Add following code to product-details.component.ts and product.component.ts to add ngAfterContentInit hook.

    --product-details.component.ts and product.component.ts
    
    ngAfterContentInit(): void{
      console.log("4 .after content init from child");
    }
    
    
  5. ngAfterContentChecked

    It is component-only hook means, not for the directive. This hook is triggered every time when the content of the component has checked by Angular's change detection mechanism. This method is called after ngAfterContentInit and every subsequent execution of ngDoCheck.

    In AfterContentChecked Angular checks the content projected into the component and it's data bound properties. Basically change detection happens on Events like click, submit or AJAX calls or Timer events.

    Add following code to product-details.component.ts

      --product-details.component.ts
      ngAfterContentChecked(): void{
        console.log("5. ngAfterContentChecked from child.");
       }
    

    Add following code to product.component.ts.

    --product.component.ts
      ngAfterContentChecked(): void{
        console.log("5. ngAfterContentChecked from parent.");
       }
    
  6. ngAfterViewInit

    This lifecycle hook is triggered only once after view and child components are initialized. This lifecycle hook is only applied to Angular Components.

    ngAfterViewInit is called when the bindings of components and child components are checked for the first time. @ViewChild() depends on this hook to render.

    To test this hook with its sequence add below code in product-details.component.ts and product.component.ts.

     --product.component.ts
     ngAfterViewInit(): void{
      console.log("6. ngAfterViewInit from parent.");
     }  
      
    
    -- product-details.component.ts
      ngAfterViewInit(): void{
        console.log("6. ngAfterViewInit from child.");
       }
      
    
    
  7. ngAfterViewChecked

    This is also a component-only hook, triggered after all the content including child components is initialized and checked.

    ngAfterViewChecked triggered after the ngAfterViewInit and every subsequent ngAfterContentChecked.

        --product.component.ts
       ngAfterViewChecked(): void{
         console.log("7. ngAfterViewChecked from parent.");
       }  
      
       -- product-details.component.ts
       ngAfterViewChecked(): void{
        console.log("7. ngAfterViewChecked from child.");
       }
    
  8. ngOnDestroy

    This is used for cleanup just before Angular destroys a directive or component. Unsubscribe Observables, services and detach event handlers to avoid memory leaks.

    ngOnDestroy is called only once just before the component is removed from DOM.

    Add the following code to parent and child components respectively. The entire code for product component is here and for product-details component is here.

     --product.component.ts 
     ngOnDestroy(): void{
      console.log("8. ngOnDestroy from parent.");
     }
     
     --product-details.component.ts
     ngOnDestroy(): void{
      console.log("8. ngOnDestroy from child.");
     } 
    
    

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee