Angular Component Lifecycle
Learn Angular Component Lifecycle Hooks from beginner to advanced with detailed lifecycle diagrams, hook execution flow, practical examples, interview questions, and best practices.
Every Angular component goes through a series of stages from the moment it is created until it is removed from the DOM. These stages are collectively known as the Angular Component Lifecycle.
Understanding the lifecycle is essential because it helps developers decide where to initialize data, respond to input changes, manipulate the DOM, subscribe to Observables, and clean up resources.
Angular lifecycle hooks are one of the most frequently asked Angular interview topics for both freshers and experienced developers.
Table of Contents
- What is Angular Lifecycle?
- Why Lifecycle Hooks?
- Lifecycle Overview
- Complete Lifecycle Flow
- Lifecycle Hooks Explained
- Hook Execution Order
- Real-World Example
- Top 10 Interview Questions
- Best Practices
- Summary
What is Angular Component Lifecycle?
The Angular Component Lifecycle is the sequence of events that Angular follows while creating, updating, rendering, and destroying a component.
During its lifetime, Angular automatically calls special methods called Lifecycle Hooks.
These hooks allow developers to execute custom logic at different stages of a component's lifecycle.
Why Lifecycle Hooks?
Lifecycle hooks allow developers to:
- Initialize component data
- Detect input property changes
- Access child components
- Manipulate the DOM safely
- Fetch data from APIs
- Subscribe to Observables
- Release resources
- Prevent memory leaks
Complete Lifecycle Overview
flowchart TD
Create["Component Created"]
Create --> Constructor
Constructor --> OnChanges
OnChanges --> OnInit
OnInit --> DoCheck
DoCheck --> AfterContentInit
AfterContentInit --> AfterContentChecked
AfterContentChecked --> AfterViewInit
AfterViewInit --> AfterViewChecked
AfterViewChecked --> UserInteraction
UserInteraction --> ChangeDetection
ChangeDetection --> DoCheck
ChangeDetection --> AfterContentChecked
ChangeDetection --> AfterViewChecked
UserInteraction --> Destroy
Destroy --> OnDestroy
Component Lifecycle Architecture
flowchart LR
Browser
Browser --> Angular
Angular --> Component
Component --> LifecycleHooks
LifecycleHooks --> RenderDOM
RenderDOM --> User
User --> ChangeDetection
ChangeDetection --> LifecycleHooks
Lifecycle Hook Order
| Order | Hook |
|---|---|
| 1 | constructor() |
| 2 | ngOnChanges() |
| 3 | ngOnInit() |
| 4 | ngDoCheck() |
| 5 | ngAfterContentInit() |
| 6 | ngAfterContentChecked() |
| 7 | ngAfterViewInit() |
| 8 | ngAfterViewChecked() |
| 9 | ngOnDestroy() |
1. constructor()
The constructor is executed when Angular creates the component instance.
constructor() {
console.log("Constructor Executed");
}
Use it for:
- Dependency Injection
- Simple initialization
Avoid:
- API calls
- Heavy logic
- DOM access
2. ngOnChanges()
Called whenever an @Input() property changes.
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
Common use cases:
- Respond to parent data changes
- Recalculate values
- Validate incoming data
3. ngOnInit()
Executed only once after Angular initializes the component.
ngOnInit(): void {
console.log("Component Initialized");
}
Ideal for:
- API calls
- Initial data loading
- Component setup
4. ngDoCheck()
Runs during every Angular change detection cycle.
ngDoCheck(): void {
console.log("Checking Changes");
}
Use carefully because it executes frequently.
5. ngAfterContentInit()
Runs after projected content (<ng-content>) is initialized.
ngAfterContentInit(): void {
console.log("Projected Content Initialized");
}
6. ngAfterContentChecked()
Runs after Angular checks projected content.
ngAfterContentChecked(): void {
console.log("Content Checked");
}
7. ngAfterViewInit()
Runs once after Angular initializes the component's view.
ngAfterViewInit(): void {
console.log("View Initialized");
}
Perfect place for:
- ViewChild
- DOM measurements
- Third-party UI libraries
8. ngAfterViewChecked()
Runs after every view check.
ngAfterViewChecked(): void {
console.log("View Checked");
}
Avoid expensive computations here.
9. ngOnDestroy()
Executed before Angular destroys the component.
ngOnDestroy(): void {
console.log("Cleanup");
}
Common tasks:
- Unsubscribe Observables
- Remove timers
- Close WebSocket connections
- Clean event listeners
Lifecycle Sequence Diagram
sequenceDiagram
participant Angular
participant Component
participant Browser
Angular->>Component: constructor()
Angular->>Component: ngOnChanges()
Angular->>Component: ngOnInit()
Angular->>Component: ngDoCheck()
Angular->>Component: ngAfterContentInit()
Angular->>Component: ngAfterContentChecked()
Angular->>Component: ngAfterViewInit()
Angular->>Component: ngAfterViewChecked()
Component->>Browser: Render UI
Browser->>Angular: User Action
Angular->>Component: Change Detection
Angular->>Component: ngDoCheck()
Angular->>Component: ngAfterContentChecked()
Angular->>Component: ngAfterViewChecked()
Angular->>Component: ngOnDestroy()
Complete Example
import {
Component,
OnInit,
OnDestroy,
OnChanges,
DoCheck,
AfterViewInit,
AfterViewChecked,
AfterContentInit,
AfterContentChecked,
Input,
SimpleChanges
} from '@angular/core';
@Component({
selector: 'app-demo',
standalone: true,
template: `<h2>Angular Lifecycle Demo</h2>`
})
export class DemoComponent
implements
OnInit,
OnDestroy,
OnChanges,
DoCheck,
AfterViewInit,
AfterViewChecked,
AfterContentInit,
AfterContentChecked {
@Input() name = '';
constructor() {
console.log('Constructor');
}
ngOnChanges(changes: SimpleChanges): void {
console.log('ngOnChanges', changes);
}
ngOnInit(): void {
console.log('ngOnInit');
}
ngDoCheck(): void {
console.log('ngDoCheck');
}
ngAfterContentInit(): void {
console.log('ngAfterContentInit');
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked');
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit');
}
ngAfterViewChecked(): void {
console.log('ngAfterViewChecked');
}
ngOnDestroy(): void {
console.log('ngOnDestroy');
}
}
Memory Leak Prevention
flowchart LR
Observable
Observable --> Subscribe
Subscribe --> Component
Component --> OnDestroy
OnDestroy --> Unsubscribe
Unsubscribe --> MemoryReleased
Example:
private subscription!: Subscription;
ngOnInit(): void {
this.subscription = this.userService.getUsers().subscribe();
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
Lifecycle Hooks Summary
| Hook | Called | Common Use |
|---|---|---|
| constructor | Component creation | Dependency Injection |
| ngOnChanges | Input changes | React to parent updates |
| ngOnInit | Once | Load data |
| ngDoCheck | Every change detection | Custom change detection |
| ngAfterContentInit | Once | Projected content initialization |
| ngAfterContentChecked | Every content check | Validate projected content |
| ngAfterViewInit | Once | Access ViewChild |
| ngAfterViewChecked | Every view check | Monitor view updates |
| ngOnDestroy | Before destruction | Cleanup resources |
Top 10 Angular Lifecycle Interview Questions
1. What is the Angular Component Lifecycle?
Answer
It is the sequence of stages that a component goes through from creation to destruction. Angular invokes lifecycle hooks automatically during these stages.
2. What is the purpose of ngOnInit()?
Answer
ngOnInit() runs once after Angular initializes the component. It is commonly used for loading data, calling APIs, and performing component initialization.
3. What is the difference between constructor() and ngOnInit()?
| constructor | ngOnInit |
|---|---|
| JavaScript/TypeScript feature | Angular lifecycle hook |
| Used for Dependency Injection | Used for initialization logic |
| Runs before Angular initialization | Runs after Angular initializes the component |
4. When is ngOnChanges() called?
Answer
It is called whenever an @Input() property changes. It receives a SimpleChanges object that describes the previous and current values.
5. What is ngDoCheck()?
Answer
ngDoCheck() is executed during every Angular change detection cycle. It is useful for implementing custom change detection but should be used carefully because it runs frequently.
6. What is ngAfterViewInit() used for?
Answer
It runs after Angular initializes the component's view. It is commonly used to access @ViewChild, measure DOM elements, or initialize third-party UI libraries.
7. Why is ngOnDestroy() important?
Answer
It is used to release resources before a component is destroyed, such as unsubscribing from Observables, clearing timers, and removing event listeners to prevent memory leaks.
8. Which lifecycle hook is called only once?
Answer
The following hooks execute only once during a component's lifetime:
ngOnInit()ngAfterContentInit()ngAfterViewInit()
9. Which hooks are executed multiple times?
Answer
These hooks can execute repeatedly:
ngOnChanges()ngDoCheck()ngAfterContentChecked()ngAfterViewChecked()
10. What is the correct lifecycle hook execution order?
Answer
- constructor()
- ngOnChanges()
- ngOnInit()
- ngDoCheck()
- ngAfterContentInit()
- ngAfterContentChecked()
- ngAfterViewInit()
- ngAfterViewChecked()
- ngOnDestroy()
Common Interview Follow-Up Questions
- What is Change Detection?
- What is
SimpleChanges? - When should you use
ViewChild? - What is content projection?
- What is the difference between content and view?
- Can
ngOnInit()run multiple times? - Which hook is best for API calls?
- Which hook is best for DOM manipulation?
- How do you avoid memory leaks?
- Why should heavy work be avoided in
ngDoCheck()?
Common Mistakes
- Calling APIs inside the constructor.
- Forgetting to unsubscribe in
ngOnDestroy(). - Performing expensive calculations inside
ngDoCheck(). - Manipulating the DOM before
ngAfterViewInit(). - Assuming
ngOnInit()runs every time data changes.
Best Practices
- Use the constructor only for dependency injection.
- Perform initialization in
ngOnInit(). - Use
ngOnChanges()to respond to input updates. - Access DOM elements only after
ngAfterViewInit(). - Always unsubscribe from Observables in
ngOnDestroy(). - Keep lifecycle hooks lightweight.
- Avoid unnecessary work during change detection.
Summary
Angular lifecycle hooks provide precise control over a component's lifecycle, from creation to destruction. By choosing the appropriate hook for initialization, change detection, DOM interaction, and cleanup, developers can build efficient, maintainable, and high-performance Angular applications. Mastering lifecycle hooks is essential for real-world development and Angular technical interviews.
Interview Cheat Sheet
| Hook | Purpose |
|---|---|
| constructor | Dependency Injection |
| ngOnChanges | Input changes |
| ngOnInit | Initialize component |
| ngDoCheck | Custom change detection |
| ngAfterContentInit | Content projection initialized |
| ngAfterContentChecked | Projected content checked |
| ngAfterViewInit | View initialized |
| ngAfterViewChecked | View checked |
| ngOnDestroy | Cleanup resources |
Next Article
➡️ 10-Angular-Interview-Top-50-Beginner-QA.md