Learn About Angular Component Hook Life Cycle

Hi Readers

I hope you are doing well. Today, I am here with one more tutorial on the Angular Component Hook Life Cycle. I hope you have liked all my previous tutorials.

Angular hook life cycle

First, I will define the Component. A component is the basic building block of an Angular application. We can say that an Angular application is a tree of components. Each component has a template.

Now, I am going to define the Angular Hook Lifecycle. A component has a lifecycle managed by Angular itself. It means any time when a component is required, Angular performs the below steps.

  • Creates the components and renders the components.
  • Creates and renders its children.
  • Check if the Data-bound property will change.
  • Destroys the component before removing it from the DOM.

 According to the above, Angular provides the Life cycle, which is the Angular Hook Life Cycle. You can understand from the below figure.

Angular Hook Lifecycle

Angular component hook lifecycle

As you can see above I have created a few hooks in different colored boxes. The light green box is for the constructor which is always called first. The dark green box denotes these hooks for both directive and component, which means these apply to both component and directive. The blue boxes denote the hook which is called only for components.  I have also marked the whole Angular Hook Lifecycle with a big rectangle in which I covered the entire lifecycle of the component.

Now I am going to define it with an example that I have created with an Angular application. I have the below files.

  • app.component.ts
    import { Component, 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 OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
      title = 'app';
      usertext: string = "";
      ngOnInit() {
        console.log('ngOnInit called');
      }
      ngDoCheck() {
        console.log('ngDoCheck called');
      }
      ngAfterContentInit() {
        console.log('ngAfterContentInit called');
      }
      ngAfterContentChecked() {
        console.log('ngAfterContentChecked called');
      }
      ngAfterViewInit() {
        console.log('ngAfterViewInit called');
      }
      ngAfterViewChecked() {
        console.log('ngAfterViewChecked called');
      }
      ngOnDestroy() {
        console.log('ngOnDestroy called');
      }
    }
  • app.component.html
    <div>
      <h2>Angular Compoent Hook LifeCycle :</h2>
    </div>
    <table style="border:1">
      <tr>
        <td>
          <h3>Parent value</h3>
        </td>
        <td>
          <input type="text" [(ngModel)]="usertext" />
        </td>
      </tr>
      <tr>
        <td>
          <h3>Child value</h3>
        </td>
        <td>
          <app-child [changedata]="usertext"></app-child>
        </td>
      </tr>
    </table>
    
  • app.child.component.ts
    import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
    @Component({
        selector: 'app-child',
        template: ` {{changedata}} `
    })
    export class ChildComponent implements OnChanges {
        @Input() changedata: string;
        ngOnChanges(changes: SimpleChanges) {
            for (let name_prop in changes) {
                let change = changes[name_prop];
                let current_value = JSON.stringify(change.currentValue);
                let previous_value = JSON.stringify(change.previousValue);
                console.log("ngOnChange is called");
                console.log("Current value is:" + current_value);
                console.log("Previous value is:" + previous_value);
            }
        }
    }
    

According to the above, we have app.component.ts and app.component.html files which I am using for the parent component and showing all the component hook life cycles.

For ngOnChange I have added an app.child.component.ts file with html which I am using for data bound property of input.

As you know first we will execute the ng serve command in the Angular CLI command window  If the application is compiled successfully then you can run the application in the browser by localhost:4200 which we will use for showing the application output.

As you can see above I have added console.log for showing the exact life cycle steps. When the application runs successfully, the console window shows the below output with localhost:4200.

Application run successfully

The above images show the lifecycle of the component hook with steps. As you can see above when the application runs successfully, the console windows show the step-by-step lifecycle hook. We can get the current value and previous value of the input with the help of the ngOnChanges hook and SimpleChanges object which get the current and previous values. First, it shows the current value is empty because the input text is blank and the previous value is undefined because we don't have the previous value at the start of the application.

Now when I enter the ‘t’  character in the input box, the ngOnChanges hook is again called and shows the current and previous values. The current value is t and the previous value is “” empty. So we can say, we can get all instances of input value when the data-bound property changes with the help of the ngOnChanges hook.

I hope you liked this -- please share it if you did. I will define the Angular Component Lifecycle Hook in my later tutorial.


Similar Articles