Angular Component Lifecycle Hooks
Master Angular Component Lifecycle Hooks with execution order, lifecycle flow diagrams, hook examples, best practices, performance tips, real-world scenarios, and interview questions.
Angular components go through several phases from creation to destruction. During each phase, Angular automatically invokes Lifecycle Hooks, allowing developers to execute custom logic at the appropriate time.
Lifecycle hooks are among the most frequently asked Angular interview topics because they directly impact application performance, change detection, DOM manipulation, API calls, and memory management.
Table of Contents
- What are Lifecycle Hooks?
- Why Lifecycle Hooks?
- Complete Lifecycle Flow
- Execution Order
- Every Lifecycle Hook Explained
- Real-World Example
- Performance Considerations
- Best Practices
- Top 10 Interview Questions
- Summary
What are Angular Lifecycle Hooks?
Lifecycle Hooks are special callback methods that Angular automatically invokes while creating, updating, rendering, and destroying a component.
These hooks allow developers to execute code at specific moments during a component's lifetime.
Examples include:
- Initializing data
- Calling REST APIs
- Detecting input changes
- Accessing DOM elements
- Cleaning subscriptions
- Preventing memory leaks
Why Lifecycle Hooks?
Lifecycle hooks help developers:
- Initialize component state
- Load remote data
- React to parent component changes
- Access child components safely
- Improve performance
- Release resources
- Prevent memory leaks
Complete Lifecycle Flow
flowchart TD
Start
Start --> 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
Lifecycle Architecture
flowchart LR
Angular
Angular --> Component
Component --> LifecycleHooks
LifecycleHooks --> DOM
DOM --> User
User --> ChangeDetection
ChangeDetection --> LifecycleHooks
Lifecycle Hook Execution Order
| Order | Hook | Called |
|---|---|---|
| 1 | constructor() | Component instance creation |
| 2 | ngOnChanges() | Input property changes |
| 3 | ngOnInit() | After initialization |
| 4 | ngDoCheck() | Every change detection |
| 5 | ngAfterContentInit() | Projected content initialized |
| 6 | ngAfterContentChecked() | Projected content checked |
| 7 | ngAfterViewInit() | Component view initialized |
| 8 | ngAfterViewChecked() | Component view checked |
| 9 | ngOnDestroy() | Before component destruction |
1. constructor()
The constructor is a TypeScript feature, not an Angular lifecycle hook.
Angular uses it to create the component object and inject dependencies.
constructor(
private userService: UserService
) {
console.log('Constructor');
}
Use Cases
- Dependency Injection
- Simple property initialization
Avoid
- HTTP calls
- DOM access
- Business logic
2. ngOnChanges()
Called whenever an @Input() property changes.
@Input()
username = '';
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
Common Uses
- Validate incoming data
- Update computed values
- React to parent component changes
3. ngOnInit()
Runs once after Angular initializes component inputs.
ngOnInit(): void {
this.loadUsers();
}
Best Uses
- API calls
- Load configuration
- Initialize forms
- Subscribe to services
4. ngDoCheck()
Runs during every Angular Change Detection cycle.
ngDoCheck(): void {
console.log("Checking");
}
Useful for custom change detection.
Avoid expensive calculations here.
5. ngAfterContentInit()
Executed once after projected content (<ng-content>) is initialized.
ngAfterContentInit(): void {
console.log("Projected content ready");
}
6. ngAfterContentChecked()
Runs whenever Angular checks projected content.
ngAfterContentChecked(): void {
}
Use sparingly because it executes frequently.
7. ngAfterViewInit()
Runs once after Angular creates the component view.
@ViewChild('inputBox')
input!: ElementRef;
ngAfterViewInit(): void {
this.input.nativeElement.focus();
}
Common Uses
- ViewChild
- DOM manipulation
- Third-party libraries
- Charts
- Maps
8. ngAfterViewChecked()
Executed whenever Angular checks the component view.
ngAfterViewChecked(): void {
}
Avoid modifying data here because it may trigger additional change detection.
9. ngOnDestroy()
Runs before Angular removes the component.
private subscription!: Subscription;
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
Cleanup Tasks
- Unsubscribe Observables
- Clear timers
- Remove listeners
- Close WebSocket connections
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 Click
Angular->>Component: Change Detection
Angular->>Component: ngDoCheck()
Angular->>Component: ngAfterContentChecked()
Angular->>Component: ngAfterViewChecked()
Angular->>Component: ngOnDestroy()
Real-World Banking Example
Consider an online banking dashboard.
flowchart TD
Login
Login --> Dashboard
Dashboard --> LoadAccounts
LoadAccounts --> LoadTransactions
LoadTransactions --> RenderCharts
RenderCharts --> UserActions
UserActions --> RefreshData
RefreshData --> Dashboard
Dashboard --> Logout
Logout --> OnDestroy
Lifecycle usage:
| Hook | Banking Example |
|---|---|
| constructor | Inject AccountService |
| ngOnInit | Load account details |
| ngOnChanges | Update selected account |
| ngAfterViewInit | Initialize charts |
| ngOnDestroy | Close WebSocket & unsubscribe |
Lifecycle Hook Frequency
| Hook | Runs Once | Runs Multiple Times |
|---|---|---|
| constructor | ✅ | ❌ |
| ngOnChanges | ❌ | ✅ |
| ngOnInit | ✅ | ❌ |
| ngDoCheck | ❌ | ✅ |
| ngAfterContentInit | ✅ | ❌ |
| ngAfterContentChecked | ❌ | ✅ |
| ngAfterViewInit | ✅ | ❌ |
| ngAfterViewChecked | ❌ | ✅ |
| ngOnDestroy | ✅ | ❌ |
Memory Leak Prevention
flowchart LR
Observable
Observable --> Subscribe
Subscribe --> Component
Component --> OnDestroy
OnDestroy --> Unsubscribe
Unsubscribe --> MemoryReleased
Example:
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.userService.getUsers()
.pipe(takeUntil(this.destroy$))
.subscribe();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
Using takeUntil() scales better than manually tracking multiple subscriptions.
Performance Tips
| Recommendation | Benefit |
|---|---|
| Keep constructor lightweight | Faster creation |
| Use ngOnInit for APIs | Cleaner initialization |
| Avoid heavy logic in ngDoCheck | Better performance |
| Minimize work in ngAfterViewChecked | Fewer rendering issues |
| Always clean subscriptions | Prevent memory leaks |
| Use OnPush where possible | Faster change detection |
Common Mistakes
- Calling APIs inside the constructor.
- Accessing
ViewChildbeforengAfterViewInit(). - Forgetting to unsubscribe.
- Heavy logic in
ngDoCheck(). - Updating component state inside
ngAfterViewChecked(). - Ignoring memory leaks.
Best Practices
- Use constructor only for Dependency Injection.
- Initialize component data in
ngOnInit(). - React to parent changes using
ngOnChanges(). - Access DOM after
ngAfterViewInit(). - Always clean up in
ngOnDestroy(). - Keep lifecycle hooks focused and lightweight.
- Prefer RxJS operators like
takeUntil()for subscription management.
Top 10 Angular Lifecycle Hook Interview Questions
1. What are Angular Lifecycle Hooks?
Answer
Lifecycle Hooks are callback methods automatically invoked by Angular during different phases of a component's life, such as creation, updates, rendering, and destruction.
2. What is the execution order of Angular lifecycle hooks?
Answer
constructor()
↓
ngOnChanges()
↓
ngOnInit()
↓
ngDoCheck()
↓
ngAfterContentInit()
↓
ngAfterContentChecked()
↓
ngAfterViewInit()
↓
ngAfterViewChecked()
↓
ngOnDestroy()
3. What is the difference between constructor() and ngOnInit()?
| constructor | ngOnInit |
|---|---|
| TypeScript feature | Angular lifecycle hook |
| Dependency Injection | Initialization logic |
| Executes first | Executes after input initialization |
| Avoid API calls | Ideal for API calls |
4. Which lifecycle hook is best for API calls?
Answer
ngOnInit() is the preferred hook because the component has been initialized and its input properties are available.
5. Which lifecycle hook is used for DOM access?
Answer
ngAfterViewInit() because the component's view and all child views have been fully initialized.
6. When is ngOnChanges() executed?
Answer
It executes whenever an @Input() property changes and receives a SimpleChanges object containing previous and current values.
7. Why should ngDoCheck() be used carefully?
Answer
It executes during every change detection cycle. Expensive computations inside it can negatively affect application performance.
8. Why is ngOnDestroy() important?
Answer
It releases resources before the component is destroyed, preventing memory leaks by unsubscribing from Observables, clearing timers, and removing event listeners.
9. Which lifecycle hooks run only once?
Answer
- constructor()
- ngOnInit()
- ngAfterContentInit()
- ngAfterViewInit()
- ngOnDestroy()
10. Which lifecycle hooks execute multiple times?
Answer
- ngOnChanges()
- ngDoCheck()
- ngAfterContentChecked()
- ngAfterViewChecked()
Interview Cheat Sheet
| Hook | Primary Purpose |
|---|---|
| constructor | Dependency Injection |
| ngOnChanges | Detect Input Changes |
| ngOnInit | Initialize Component |
| ngDoCheck | Custom Change Detection |
| ngAfterContentInit | Content Projection Ready |
| ngAfterContentChecked | Projected Content Checked |
| ngAfterViewInit | View Ready |
| ngAfterViewChecked | View Checked |
| ngOnDestroy | Cleanup Resources |
Summary
Angular Lifecycle Hooks provide a structured way to execute logic during a component's lifecycle. Choosing the correct hook for initialization, responding to input changes, interacting with the DOM, and cleaning up resources helps build scalable, high-performance Angular applications. Understanding the purpose, execution order, and best practices of each lifecycle hook is essential for both enterprise development and Angular interviews.
Key Takeaways
- Lifecycle hooks are automatically called by Angular.
- Use constructor() only for Dependency Injection.
- Use ngOnInit() for initialization and API calls.
- Use ngOnChanges() to respond to
@Input()updates. - Use ngAfterViewInit() for DOM and
@ViewChildaccess. - Use ngOnDestroy() to clean up subscriptions and resources.
- Avoid expensive operations in frequently called hooks such as
ngDoCheck()andngAfterViewChecked().
Next Article
➡️ 13-Component-Communication-QA.md