Life cycle hooks in Angular

Bittu Kumar
2 min readAug 30, 2024

--

Angular lifecycle hooks are methods that allow you into different stages of an Angular component’s lifecycle. These hooks give you the ability to act on a component during creation, change detection, and destruction.

ngOnChange
Runs every time the component’s inputs have changed.

ngOnInit
Runs once after Angular has initialized all the component’s inputs.

ngDoCheck
Runs every time this component is checked for changes. (Not recommended )

ngAfterContentInit
Runs once after the component’s content has been initialized. ( ng-content )

ngAfterContentChecked
Runs every time this component content has been checked for changes.

ngAfterViewInit
Runs once after the component’s view has been initialized.

ngAfterViewChecked
Runs every time the component’s view has been checked for changes.

ngOnDestroy
Runs once before the component is destroyed.

Lets understand with example:

// app component html 
<app-lifecycle-hooks [message]="title"> <p>Projected content.</p></app-lifecycle-hooks>
<input [(ngModel)]="title" placeholder="Enter a name">

// app component ts
title: string = 'crud-app-angular';


// life cycle hooks component html
<p>lifecycle-hooks works!</p>
<ng-content></ng-content>

// life cycle hooks component ts
export class LifecycleHooksComponent {

@Input() message: string | undefined;

constructor() {
console.log('Constructor: Component is being created');
}

ngOnInit() {
console.log(this.message)
console.log('2: ngOnInit: Component initialized');
}


ngOnChanges(changes: SimpleChanges) {
console.log('1: ngOnChanges: Input properties changed');
console.log("ngonchange",this.message)
console.log("current value",changes['message'].currentValue);
console.log("previous value",changes['message'].previousValue);
}


ngDoCheck() {
console.log('3: ngDoCheck: Component is being checked');
}

ngAfterContentInit() {
console.log('4: ngAfterContentInit: Component content is initialized');
}

ngAfterContentChecked() {
console.log('5: ngAfterContentChecked: Component content is checked');
}

ngAfterViewInit() {
console.log('6: ngAfterViewInit: Component view is initialized');
}

ngAfterViewChecked() {
console.log('7: ngAfterViewChecked: Component view is checked');
}

ngOnDestroy() {
console.log('8: ngOnDestroy: Component is about to be destroyed');
}
}

Now we will observe console.log in two situation

  1. Once component initialized first time,

Now change something in input field:

you will observe that only onchange and checked related life cycle hooks.

I would suggest you the copy-paste this code in your angular project, change the input field value. It will be more clear to you.

Thanks for reading, Reach me out here for more discussion related to angular.

www.linkedin.com/in/bittukumar-web

--

--

Bittu Kumar
Bittu Kumar

Written by Bittu Kumar

Exploring Angular and Frontend development.

No responses yet