ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Component Life Cycle Hooks in Angular

In this tutorial, we learn how to use Angular lifecycle hooks. The life cycle hooks are the methods that angular invokes on the directives and components as it creates, changes, and destroys them. Using lifecycle hooks we can fine-tune the behavior of our components during its creation, updating, and destruction.

What is Angular Component lifecycle hooks

When the angular application starts, it creates and renders the root component. It then creates and renders its Children & their children. It forms a tree of components.

Once Angular loads the components, it starts rendering the view. To do that, it needs to check the input properties, evaluate the data bindings & expressions, render the projected content, etc. Angular also removes the component from the DOM when it no longer needs it.

Angular lets us know when these events happen using lifecycle hooks

The Angular life cycle hooks are nothing but callback functions, which angular invokes when a specific event occurs during the component’s life cycle.

For example,

  1. ngOnInit when Angular initializes the component for the first time.
  2. When a component’s input property change, Angular invokes ngOnChanges
  3. If the component is destroyed, Angular invokes ngOnDestroy

Angular lifecycle hooks

Here is the complete list of life cycle hooks, which angular invokes during the component life cycle. Angular invokes them when a specific event occurs.

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. ngOnDestroy

Change detection Cycle

Before diving into the lifecycle hooks, we need to understand the change detection cycle.

Change detection is the mechanism by which angular keeps the template in sync with the component

Consider the following code.

                              
 
<div>Hello {{name}}</div>
                            
                        

Angular updates the DOM whenever the value of the name changes. And it does it instantly.

How does angular know when the value of the name changes? It does so by running a change detection cycle on every event that may result in a change. It runs on every input change, DOM event, and timer event like setTimeout(), setInterval(), HTTP requests, etc.

During the change detection cycle, angular checks every bound property in the template with that of the component class. If it detects any changes, it updates the DOM.

Angular raises the life cycle hooks during the critical stages of the change detection mechanism.

Constructor

The life cycle of a component begins when Angular creates the component class. The first method that gets invoked is class Constructor.

Constructor is neither a life cycle hook nor is it specific to Angular. It is a Javascript feature. It is a method that is invoked when a class is created.

Angular makes use of a constructor to inject dependencies.

At this point, none of the component’s input properties are available. Neither its child components are constructed. Projected contents are also not available.

Hence there is little you can do with this method. And also, it is recommended not to use it

Once Angular instantiates the class, It kick-starts the first change detection cycle of the component.

ngOnChanges

The Angular invokes the ngOnChanges life cycle hook whenever any data-bound input property of the component or directive changes. Initializing the Input properties is the first task angular carries during the change detection cycle. And if it detects any change in property, then it raises the ngOnChanges hook. It does so during every change detection cycle.This hook is not raised if change detection does not detect any changes.

Input properties are those properties which we define using the @Input decorator. It is one of the ways by which a parent communicates with the child component.

In the following example, the child component declares the property message as the input property

                              
 
@Input() message:string
                            
                        

The parent can send the data to the child using the property binding, as shown below.

                              
    <!--code box  -->
                        <div class="example break">
                            <div class="codebox">
                                <div class="codebox-title">
                                    <h4>Example</h4><a
                                        href="../codelab.php?topic=javascript&file=sort-an-array-alphabetically"
                                        target="_blank" class="try-btn" title="Try this code using online Editor">Try
                                        this
                                        code
                                        <span>»</span></a>
                                </div>
                                <pre class="syntax-highlighter line-numbers language-javascript" style="tab-size:1;">
                            <code class="language-javascript">  
 
<app-child [message]="message">
</app-child>
 
                            </code>
                        </pre>
                            </div>
                        </div>
                        <!--End of codebox-->
                            
                        

The change detector checks if the parent component changes such input properties of a component. If it is, then it raises the ngOnChanges hook.

We use this life cycle hook in the tutorial Passing data to the child component.

The change detector uses the === strict equality operator for detecting changes. Hence for objects, the hook is fired only if the references are changed. You can read more about it from Why ngOnChanges does not fire.

ngOnInit

The Angular raises the ngOnInit hook after it creates the component and updates its input properties. It raises it after the ngOnChanges hook.

This hook is fired only once and immediately after its creation (during the first change detection).

This is a perfect place where you want to add any initialization logic for your component. Here you have access to every input property of the component. You can use them in HTTP get requests to get the data from the back-end server or run some initialization logic etc.

But note that none of the child components or projected content are available at this juncture. Hence any properties we decorate with @ViewChild, @ViewChildren, @ContentChild& @ContentChildren will not be available to use.

ngDoCheck

The Angular invokes the ngDoCheck hook event during every change detection cycle. This hook is invoked even if there is no change in any of the properties.

Angular invoke it after the ngOnChanges & ngOnInit hooks.

Use this hook to Implement a custom change detection whenever Angular fails to detect the changes made to Input properties. This hook is convenient when you opt for the Onpush change detection strategy.

The Angular ngOnChanges hook does not detect all the changes made to the input properties.

ngAfterContentInit

ngAfterContentInit Life cycle hook is called after the Component’s projected content has been fully initialized. Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook. This hook is also raised, even if there is no content to project.

The content here refers to the external content injected from the parent component via Content Projection.

The Angular Components can include the ng-content element, which acts as a placeholder for the content from the parent as shown below

                              

<h2>Child Component</h2>
<ng-content></ng-content>   <!-- placehodler for content from parent -->
 
                            
                        

The parent injects the content between the opening & closing element. Angular passes this content to the child component

                              
 
<h1>Parent Component</h1>
<app-child> This <b>content</b> is injected from parent</app-child>
 
                            
                        

During the change detection cycle, Angular checks if the injected content has changed and updates the DOM.

This is a component-only hook.

ngAfterContentChecked

ngAfterContentChecked Life cycle hook is called during every change detection cycle after Angular finishes checking of component’s projected content. Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook. Angular calls this hook even if there is no projected content in the component.

This hook is very similar to the ngAfterContentInit hook. Both are called after the external content is initialized, checked & updated. The only difference is that ngAfterContentChecked is raised after every change detection cycle. While ngAfterContentInit during the first change detection cycle.

This is a component-only hook.

ngAfterViewInit

ngAfterViewInit hook is called after the Component’s View & all its child views are fully initialized. Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.

The View here refers to the template of the current component and all its child components & directives.

This hook is called during the first change detection cycle, where angular initializes the view for the first time.

At this point, all the lifecycle hook methods & change detection of all child components & directives are processed & Component is entirely ready.

This is a component-only hook.

ngAfterViewChecked

The Angular fires this hook after it checks & updates the component’s views and child views. This event is fired after the ngAfterViewInit and after that, during every change detection cycle.

This hook is very similar to the ngAfterViewInit hook. Both are called after all the child components & directives are initialized and updated. The only difference is that ngAfterViewChecked is raised during every change detection cycle. While ngAfterViewInit during the first change detection cycle.

This is a component-only hook.

ngOnDestroy

This hook is called just before the Component/Directive instance is destroyed by Angular

You can Perform any cleanup logic for the Component here. This is where you would like to Unsubscribe Observables and detach event handlers to avoid memory leaks.

How to Use Lifecycle Hooks

  1. Import Hook interfaces
  2. Declare that Component/directive Implements lifecycle hook interface
  3. Create the hook method

Let us build a simple component, which implements the ngOnInit hook

Create a Angular Project using Angular Cli. Open the app.component.ts

Import Hook interfaces

Import hook interfaces from the core module. The name of the Interface is hook name without ng. For example interface of the ngOnInit hook is OnInit.

                              

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

Component Implements lifecycle hook interface

Next, define the AppComponent to implement OnInit interface

                              

export class AppComponent implements OnInit {
                            
                        

Create the hook method

The life cycle hook methods must use the same name as the hook.

                              

 ngOnInit() {
    console.log("AppComponent:OnInit");
  }
 
                            
                        

The complete code for the app.component.ts.

                              
 
import { Component,OnInit } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
      <h2>Life Cycle Hook</h2>` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  constructor() {
    console.log("AppComponent:Constructor");
  }
 
  ngOnInit() {
    console.log("AppComponent:OnInit");
  }
 
}
 
                            
                        

Now, run the code and open the developer console. you will see the following

                              

AppComponent:Constructor
AppComponent:OnInit
 
                            
                        

Note that the constructor event is fired before the OnInit hook.

The Order of Execution of Life Cycle Hooks

The Angular executes the hooks in the following order

On Component Creation

  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
  6. AfterViewInit
  7. AfterViewChecked

When the Component with Child Component is created

  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
  6. AfterViewInit
  7. AfterViewChecked
  1. Child Component -> OnChanges
  2. Child Component -> OnInit
  3. Child Component -> DoCheck
  4. Child Component -> AfterContentInit
  5. Child Component -> AfterContentChecked
  6. Child Component -> AfterViewInit
  7. Child Component -> AfterViewChecked
  1. AfterViewInit
  2. AfterViewChecked

After The Component is Created

  1. Child Component -> OnChanges
  2. Child Component -> OnInit
  3. Child Component -> AfterContentChecked
  4. Child Component -> AfterViewChecked

Angular Lifecycle hook Example

app.component.ts

                              
 
import { ChangeDetectionStrategy, Component, VERSION } from "@angular/core";
 
@Component,({
  selector: "my-app",
  changeDetection:ChangeDetectionStrategy.Default,
  template: `
    <h1>Angular Life Cycle Hooks</h1>
    Reference :
    <a
      href="https://www.tektutorialshub.com/angular/angular-component-life-cycle-hooks/#create-the-hook-method"
      >Angular Life Cycle Hooks</a
    >
 
    <h1>Root Component</h1>
 
 
    <br />
    <input
      type="text"
      name="message"
      [(ngModel)]="message"
      autocomplete="off"
    />
    <br />
    <input
      type="text"
      name="content"
      [(ngModel)]="content"
      autocomplete="off"
    />
 
 
    <br />
    hide child :
    <input
      type="checkbox"
      name="hideChild"
      [(ngModel)]="hideChild"
      autocomplete="off"
    />
 
    <br />
    <br />
    <app-child [message]="message" *ngIf="!hideChild">
      <!-- Injected Content -->
      <b> {{ content }} </b>
    </app-child>
 
    
  `
})
export class AppComponent {
  name = "Angular " + VERSION.major;
 
  message = "Hello";
  content = "Hello";
  hideChild=false;
 
  constructor() {
    console.log("AppComponent:Contructed");
  }
 
  ngOnChanges() {
    console.log("AppComponent:ngOnChanges");
  }
 
  ngOnInit() {
    console.log("AppComponent:ngOnInit");
  }
 
  ngDoCheck() {
    console.log("AppComponent:DoCheck");
  }
 
  ngAfterContentInit() {
    console.log("AppComponent:ngAfterContentInit");
  }
 
  ngAfterContentChecked() {
    console.log("AppComponent:AfterContentChecked");
  }
 
  ngAfterViewInit() {
    console.log("AppComponent:AfterViewInit");
  }
 
  ngAfterViewChecked() {
    console.log("AppComponent:AfterViewChecked");
  }
 
  ngOnDestroy() {
    console.log("AppComponent:ngOnDestroy");
  }
 
}
                            
                        
  • We are listening to all the hooks and logging them to the console.
  • There are two form fields message & content. We pass both to the child component. One as input property & the other via content projection
  • Using the hideChild form field, we can add or remove the ChildComponent from the DOM. We are making use of the ngIf directive.
  • We pass the message property to ChildComponent using Property binding.
  • The content property is passed as projected content.
  • child.component.ts

                                  
    
     
    import { ChangeDetectionStrategy, Component, Input,  OnInit } from '@angular/core';
    import { Customer } from './customer';
     
    @Component,({
      selector: 'app-child',
      changeDetection:ChangeDetectionStrategy.Default,
      template: `
      
          <h2>child component</h2>
     
          <br>
          <!-- Data as a input -->
          Message from Parent via @input {{message}}
          <br><br>
          <!-- Injected Content -->
          Message from Parent via content injection
          <ng-content></ng-content>
     
          <br><br><br>
          Code :
          <input type="text" name="code" [(ngModel)]="customer.code" autocomplete="off">
          <br><br>
          Name:
          <input type="text" name="name" [(ngModel)]="customer.name" autocomplete="off">
     
          <app-grand-child [customer]="customer"></app-grand-child>
      
      `
      
    })
    export class ChildComponent {
     
      @Input() message:string
     
      customer:Customer = new Customer()
     
     
    constructor() {
        console.log("  ChildComponent:Contructed");
      }
     
      ngOnChanges() {
        console.log("  ChildComponent:ngOnChanges");
      }
     
      ngOnInit() {
        console.log("  ChildComponent:ngOnInit");
      }
     
      ngDoCheck() {
        console.log("  ChildComponent:DoCheck");
      }
     
      ngAfterContentInit() {
        console.log("  ChildComponent:ngAfterContentInit");
      }
     
      ngAfterContentChecked() {
        console.log("  ChildComponent:AfterContentChecked");
      }
     
      ngAfterViewInit() {
        console.log("  ChildComponent:AfterViewInit");
      }
     
      ngAfterViewChecked() {
        console.log("  ChildComponent:AfterViewChecked");
      }
     
      ngOnDestroy() {
        console.log("  ChildComponent:ngOnDestroy");
      }
     
    }
                                
                            
  • We are listening to all the hooks
  • @Inputdecorator marks the message as input property. It will receive the data from the parent
  • <ng-content> <ng-content> is the place holder to receive the projected content from the parent.
  • Two forms fields for customer object, which we pass it to the GrandChildComponent
  • grandchild.component.ts
                                  
    
    import { ChangeDetectionStrategy, Component, Input,  OnInit } from '@angular/core';
    import { Customer } from './customer';
     
    @Component({
      selector: 'app-grand-child',
      changeDetection:ChangeDetectionStrategy.Default,
      template: `
      
          <h3>grand child component </h3>
     
          <br>
          Name {{customer.name}}
      
      `,
    })
    export class GrandChildComponent {
     
     
      @Input() customer:Customer
      
      constructor() {
        console.log("    GrandChildComponent:Contructed");
      }
     
      ngOnChanges() {
        console.log("    GrandChildComponent:ngOnChanges");
      }
     
      ngOnInit() {
        console.log("    GrandChildComponent:ngOnInit");
      }
     
     
      ngDoCheck() {
        console.log("    GrandChildComponent:DoCheck");
      }
     
      ngAfterContentInit() {
        console.log("    GrandChildComponent:ngAfterContentInit");
      }
     
      ngAfterContentChecked() {
        console.log("    GrandChildComponent:AfterContentChecked");
      }
     
      ngAfterViewInit() {
        console.log("    GrandChildComponent:AfterViewInit");
      }
     
      ngAfterViewChecked() {
        console.log("    GrandChildComponent:AfterViewChecked");
      }
     
      ngOnDestroy() {
        console.log("    GrandChildComponent:ngOnDestroy");
      }
     
     
     
    }
                                
                            
  • We are listening to all the hooks
  • @Inputdecorator marks the customer as input property. It will receive the data from the parent
  • Run the code and check the console for the log messages

    Conclusion

    We learned about Component life cycle hooks in Angular. The Angular generates the following hooks OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked & OnDestroy. We then learned how to build an Application using the OnInit life cycle hook. Finally, we looked at the Order of execution of these life cycle hooks