Saturday, July 4, 2026

Angular Lifecycle Hooks – Complete Guide with Real-Time Examples (Angular 16/17/18+)

 Angular Lifecycle Hooks are special methods that Angular automatically calls during the lifecycle of a component.

Think of a component like a person.

  • Born → Constructor

  • Gets Data → ngOnInit

  • Receives Updates → ngOnChanges

  • Checks Changes → ngDoCheck

  • Displays Content → ngAfterViewInit

  • Destroyed → ngOnDestroy


Angular Component Lifecycle

Constructor
      │
      ▼
ngOnChanges
      │
      ▼
ngOnInit
      │
      ▼
ngDoCheck
      │
      ▼
ngAfterContentInit
      │
      ▼
ngAfterContentChecked
      │
      ▼
ngAfterViewInit
      │
      ▼
ngAfterViewChecked
      │
      ▼
ngOnDestroy

1. Constructor

Purpose

The constructor is the first method executed when Angular creates a component.

Used for:

  • Dependency Injection

  • Initializing services

  • Basic variable initialization

Example

constructor(private employeeService: EmployeeService) {
    console.log("Constructor Called");
}

Output

Constructor Called

Real-Time Example

Imagine opening Amazon.

When the page loads,

Angular creates ProductComponent.

Before displaying products,

Angular injects

  • ProductService

  • CartService

  • LoggerService

using Constructor.

Amazon Page

↓

Constructor

↓

Inject Services

↓

Load Component

2. ngOnChanges()

Purpose

Called whenever an Input property changes.

Only works with @Input().

Example

Parent Component

<app-child [employee]="employee"></app-child>

Child Component

@Input() employee:any;

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

Output

Employee Changed

Real-Time Example

Employee Portal

Manager selects another employee.

Employee 101

↓

Employee 205

↓

Child Component Updated

↓

ngOnChanges()

Perfect example

Employee Details Screen


3. ngOnInit()

Purpose

Runs only once after Angular initializes the component.

Most commonly used hook.

Used for

  • API Calls

  • Loading data

  • Initial calculations

Example

ngOnInit(){

   this.loadEmployees();

}
GET /api/employees

Real-Time Banking Example

Customer Dashboard

After login

Angular calls

GET Account Details

GET Transactions

GET Loans

inside

ngOnInit()

4. ngDoCheck()

Purpose

Custom change detection.

Angular calls this hook during every change detection cycle.

Example

ngDoCheck(){

   console.log("Checking Changes");

}

Real-Time Example

Shopping Cart

User changes

  • Quantity

  • Price

  • Coupon

Angular continuously checks

Subtotal

GST

Discount

Final Amount

using ngDoCheck()


5. ngAfterContentInit()

Purpose

Runs once after external content is projected using

<ng-content>

Example

<app-card>

   <h2>Employee Information</h2>

</app-card>

Card Component

<div class="card">

<ng-content></ng-content>

</div>
ngAfterContentInit(){

console.log("Content Loaded");

}

Real-Time Example

Dashboard Card

Employee Name

Employee Salary

Employee Department

are projected into Card Component.

Angular executes

ngAfterContentInit()

6. ngAfterContentChecked()

Runs after every content check.

Example

ngAfterContentChecked(){

console.log("Content Checked");

}

Real-Time Example

Employee Dashboard

Manager changes employee role.

Projected content updates.

Angular verifies projected content.


7. ngAfterViewInit()

Purpose

Runs after the component view is fully initialized.

Most commonly used for

  • ViewChild

  • Charts

  • Google Maps

  • DataTables

Example

@ViewChild('txtName')
name!:ElementRef;

ngAfterViewInit(){

this.name.nativeElement.focus();

}

Real-Time Example

Login Page

Cursor automatically focuses on

Username textbox.

Username

Password

Angular waits until UI is created.

Then

Focus()

inside

ngAfterViewInit()

8. ngAfterViewChecked()

Runs every time Angular checks component view.

Example

ngAfterViewChecked(){

console.log("View Checked");

}

Real-Time Example

Dashboard

Charts

Tables

Graphs

Whenever data changes,

Angular checks the whole view.


9. ngOnDestroy()

Purpose

Called before Angular destroys the component.

Used for cleanup.

Very important.

Used for

  • Unsubscribe Observable

  • Clear Timer

  • Remove Event Listener

  • Close SignalR Connection

  • Close WebSocket

Example

subscription!:Subscription;

ngOnInit(){

this.subscription=this.employeeService.getEmployees()
.subscribe();

}

ngOnDestroy(){

this.subscription.unsubscribe();

}

Real-Time Banking Example

Customer Dashboard

User logs out.

Angular

Disconnect SignalR

Stop Timer

Unsubscribe API

Remove Events

Destroy Component

Complete Real-Time Employee Management Example

Employee List

constructor()

↓

Inject EmployeeService

↓

ngOnInit()

↓

Call Employee API

↓

Display Employees

↓

Manager selects employee

↓

ngOnChanges()

↓

Employee Details Updated

↓

User edits salary

↓

ngDoCheck()

↓

Salary recalculated

↓

Dashboard Card Loaded

↓

ngAfterContentInit()

↓

Chart Loaded

↓

ngAfterViewInit()

↓

User navigates away

↓

ngOnDestroy()

↓

Unsubscribe APIs

Complete Sample Component

import {
 Component,
 OnInit,
 OnChanges,
 DoCheck,
 AfterContentInit,
 AfterContentChecked,
 AfterViewInit,
 AfterViewChecked,
 OnDestroy,
 Input,
 SimpleChanges
} from '@angular/core';

@Component({
 selector:'app-employee',
 templateUrl:'employee.component.html'
})
export class EmployeeComponent
implements
OnInit,
OnChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy{

 @Input() employee:any;

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

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

 ngOnInit(){
   console.log("ngOnInit");
 }

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

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

 ngAfterContentChecked(){
   console.log("ngAfterContentChecked");
 }

 ngAfterViewInit(){
   console.log("ngAfterViewInit");
 }

 ngAfterViewChecked(){
   console.log("ngAfterViewChecked");
 }

 ngOnDestroy(){
   console.log("ngOnDestroy");
 }

}

Execution Order (First Time)

OrderLifecycle HookPurpose
1ConstructorCreate component and inject dependencies
2ngOnChangesDetect initial @Input() values
3ngOnInitInitialize component and load data
4ngDoCheckPerform custom change detection
5ngAfterContentInitInitialize projected content (<ng-content>)
6ngAfterContentCheckedCheck projected content
7ngAfterViewInitInitialize component view and child views
8ngAfterViewCheckedCheck the component view
9ngOnDestroyClean up resources before destruction

Which Hook to Use?

ScenarioRecommended Hook
Inject servicesconstructor()
Load API datangOnInit()
Detect @Input() changesngOnChanges()
Custom change detectionngDoCheck()
Work with projected contentngAfterContentInit()
Access @ViewChild or initialize UI librariesngAfterViewInit()
Subscribe to observablesngOnInit()
Unsubscribe, clear timers, close connectionsngOnDestroy()

Common Interview Questions

1. What is the difference between constructor() and ngOnInit()?

ConstructorngOnInit
JavaScript/TypeScript featureAngular lifecycle hook
Used for dependency injectionUsed for component initialization
Runs before Angular initializes the componentRuns after Angular has initialized inputs
Avoid API calls hereIdeal place for API calls

2. Which hook is best for calling APIs?

Answer: ngOnInit().

3. Which hook is used for cleanup?

Answer: ngOnDestroy().

4. Which hook is used with @ViewChild?

Answer: ngAfterViewInit().

5. Which hook is called when an @Input() value changes?

Answer: ngOnChanges().

6. Which lifecycle hook is called only once after component initialization?

Answer: ngOnInit().

7. Why is ngOnDestroy() important?

Answer: It prevents memory leaks by unsubscribing from observables, clearing timers, removing event listeners, and closing WebSocket or SignalR connections.


Best Practices

  • Use constructor() only for dependency injection and simple initialization.

  • Place API calls and business initialization logic in ngOnInit().

  • Keep ngDoCheck() lightweight because it runs frequently.

  • Use ngAfterViewInit() when interacting with the DOM or @ViewChild.

  • Always clean up subscriptions and resources in ngOnDestroy().

  • Avoid performing expensive operations inside ngAfterViewChecked() and ngAfterContentChecked() since they are called often.

This lifecycle knowledge is frequently tested in Angular interviews and is essential for building efficient, maintainable Angular applications.

No comments:

Don't Copy

Protected by Copyscape Online Plagiarism Checker