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:
- Constructor: Called when page loads at first time. Called only one time.
- 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
- ngOnInit: Called once the component is initialized. Ideal for setting up the component’s state.
- ngDoCheck: Used to detect changes manually (called with each change detection cycle).
- ngAfterContentInit: Called after the content is projected into the component.
- ngAfterContentChecked: Called after the projected content is checked.
- ngAfterViewInit: Called after the view has been initialized.
- ngAfterViewChecked: Called after Angular checks the component’s view.
- ngOnDestroy: Called just before the component is destroyed. Use it to clean up resources, like unsubscribing from observables.
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;
}
}
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>
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 {
}
}
child.component.html
<div>
Input Value: <strong>{{inputValue}}</strong>
</div>
We will have output like this:
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 {}
}
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 {}
}
Again I have inputed the value and again ngOnChanges called but constructor only called once.
Let's see what we have in changes argument:
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called", changes);
}
Let's put some value and see:
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");
}
}
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");
}
}
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>
parent.component.html
<app-child [inputValue]="value"> Content </app-child>
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");
}
}
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");
}
}
let's play around this:
<app-child [inputValue]="value"> Content: {{value}} </app-child>
When there is change in ng-content again ngAfterContentChecked called.
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.
8.ngAfterViewChecked
- Invoked after every check of the component's view and its child views.
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;
}
}
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>
Before we click the Destroy component button:
After we click the Destroy component button:
Lifecycle Hook Sequence:
- Constructor
- ngOnChanges (if @Input properties exist)
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
By understanding and using these hooks effectively, you can manage the component's behavior at different stages of its lifecycle.
Top comments (0)