DEV Community

Cover image for Component Lifecycle in Angular
Renuka Patil
Renuka Patil

Posted on

Component Lifecycle in Angular

Angular lifecycle hooks are methods that allow developers to tap into key moments of an Angular component’s life cycle, from its creation to its destruction which includes initialization, changes, and destruction. The most commonly used lifecycle hooks are:

  1. Constructor: Called when page loads at first time. Called only one time.
  2. ngOnChanges: Execute multiple times. first time will execute when component created/loaded. When there is change in custom property with @input decorator that every time this hook will called. worked with argument - simple changes
  3. ngOnInit: Called once the component is initialized. Ideal for setting up the component’s state.
  4. ngDoCheck: Used to detect changes manually (called with each change detection cycle).
  5. ngAfterContentInit: Called after the content is projected into the component.
  6. ngAfterContentChecked: Called after the projected content is checked.
  7. ngAfterViewInit: Called after the view has been initialized.
  8. ngAfterViewChecked: Called after Angular checks the component’s view.
  9. ngOnDestroy: Called just before the component is destroyed. Use it to clean up resources, like unsubscribing from observables.

Image description

Before dive in, lets create prerequisite project:
We will need parent and child component. We will have Input field in parent component and will pass that inputed value to the child and will show in child component.

parent.component.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  value:string = '';
  SubmitValue(val: any) {
    this.value = val.value;
  }

}

Enter fullscreen mode Exit fullscreen mode

parent.component.html


<h1>Lifecycle Hooks</h1>

<input type="text" placeholder="Input here..." #val>
<button (click)="SubmitValue(val)">Submit Value</button>

<br><br>
<app-child [inputValue]="value"></app-child>
Enter fullscreen mode Exit fullscreen mode

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {
  }

}

Enter fullscreen mode Exit fullscreen mode

child.component.html

<div>
    Input Value: <strong>{{inputValue}}</strong>
</div>
Enter fullscreen mode Exit fullscreen mode

We will have output like this:

Image description

1.Constructor

  • The constructor is a TypeScript class method used to initialize a component. It is called before any Angular lifecycle hooks.
  • Primary use: Initialize dependency injection and set up variables.
export class ChildComponent implements OnInit {

  constructor() {
    **console.log("Constructor Called");**
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {}

}
Enter fullscreen mode Exit fullscreen mode

Image description

2.ngOnChanges

  • Invoked when any input properties of a component are changed.
  • Provides a SimpleChanges object containing the previous and current values of the input properties.
  • Usage: Update the data input property from the parent component to trigger this hook.
export class ChildComponent implements OnInit, OnChanges {

  constructor() {
    console.log("Constructor Called");
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called");
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {}

}
Enter fullscreen mode Exit fullscreen mode

Image description

Again I have inputed the value and again ngOnChanges called but constructor only called once.

Image description

Let's see what we have in changes argument:

 ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called", changes);
  }
Enter fullscreen mode Exit fullscreen mode

Image description

Let's put some value and see:

Image description

3.ngOnInit

  • Called once after the first ngOnChanges.
  • Primary use: Initialize the component and set up any necessary data for rendering.
export class ChildComponent implements OnInit, OnChanges {

  constructor() {
    console.log("Constructor Called");
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called");
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {
    console.log("ngOnInit Called");
  }

}
Enter fullscreen mode Exit fullscreen mode

Image description

4.ngDoCheck

  • Runs every time Angular detects a change in the component or its children.
  • Use this for custom change detection logic.
export class ChildComponent implements OnInit, OnChanges, DoCheck {

  constructor() {
    console.log("Constructor Called");
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called", changes);
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {
    console.log("ngOnInit Called");
  }

  ngDoCheck() {
    console.log("ngDoCheck Called");
  }

}

Enter fullscreen mode Exit fullscreen mode

Image description

5.ngAfterContentInit

  • Called once after content (e.g., <ng-content>) is projected into the component.

child.component.html

<div>
    Input Value: <strong>{{inputValue}}</strong>

    <ng-content></ng-content>
</div>
Enter fullscreen mode Exit fullscreen mode

parent.component.html

<app-child [inputValue]="value"> Content </app-child>
Enter fullscreen mode Exit fullscreen mode

child.component.ts

export class ChildComponent implements OnInit, OnChanges, DoCheck, AfterContentInit {

  constructor() {
    console.log("Constructor Called");
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called", changes);
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {
    console.log("ngOnInit Called");
  }

  ngDoCheck() {
    console.log("ngDoCheck Called");
  }

  ngAfterContentInit() {
    console.log("ngAfterContentInit Called");
  }

}

Enter fullscreen mode Exit fullscreen mode

Image description

6.ngAfterContentChecked

  • Called after every check of the projected content.
  • Use sparingly to avoid performance issues.
export class ChildComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked {

  constructor() {
    console.log("Constructor Called");
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called", changes);
  }

  @Input() inputValue: string = "LifeCycle Hooks";

  ngOnInit(): void {
    console.log("ngOnInit Called");
  }

  ngDoCheck() {
    console.log("ngDoCheck Called");
  }

  ngAfterContentInit() {
    console.log("ngAfterContentInit Called");
  }

  ngAfterContentChecked(): void {
    console.log("ngAfterContentChecked Called");
  }

}
Enter fullscreen mode Exit fullscreen mode

Image description

let's play around this:

<app-child [inputValue]="value"> Content: {{value}} </app-child>
Enter fullscreen mode Exit fullscreen mode

When there is change in ng-content again ngAfterContentChecked called.

Image description

7.ngAfterViewInit

  • Called once after the component's view and its child views have been initialized.
  • Useful for initializing third-party libraries or DOM manipulations.

Image description

8.ngAfterViewChecked

  • Invoked after every check of the component's view and its child views.

Image description

9.ngOnDestroy

  • Called just before the component is destroyed.
  • Use it for cleanup tasks like unsubscribing from Observables or detaching event listeners.

ngOnDestroy will only called when we destroy any component, so let's try to remove child component when we click Destroy component button.
Let's make arrangements:

parent.component.ts

export class ParentComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  value:string = '';
  childExist: boolean = true;
  SubmitValue(val: any) {
    this.value = val.value;
  }

  destroyComponet() {
    this.childExist = false;

  }
}
Enter fullscreen mode Exit fullscreen mode

parent.component.html


<h1>Lifecycle Hooks</h1>

<input type="text" placeholder="Input here..." #val>
<button (click)="SubmitValue(val)">Submit Value</button>

<br><br>
<app-child *ngIf="childExist" [inputValue]="value"> Content: {{value}} </app-child>


<br><br>
<button (click)="destroyComponet()">Destroy component</button>
Enter fullscreen mode Exit fullscreen mode

Before we click the Destroy component button:

Image description

After we click the Destroy component button:

Image description

Lifecycle Hook Sequence:

  1. Constructor
  2. ngOnChanges (if @Input properties exist)
  3. ngOnInit
  4. ngDoCheck
  5. ngAfterContentInit
  6. ngAfterContentChecked
  7. ngAfterViewInit
  8. ngAfterViewChecked
  9. ngOnDestroy

By understanding and using these hooks effectively, you can manage the component's behavior at different stages of its lifecycle.

Top comments (0)