DEV Community

Cover image for Angular Component Lifecycle: Mastering the 11-Step Sequence (Code Examples Included)
Md Habibur Rahman
Md Habibur Rahman

Posted on

Angular Component Lifecycle: Mastering the 11-Step Sequence (Code Examples Included)

"As developers, we need precision. This guide details the exact 11-step lifecycle sequence of an Angular component, straight from the official docs. We'll show you when to check content vs. the view, why certain hooks run repeatedly, and the critical cleanup step to eliminate memory leaks."

The Angular lifecycle is the engine of your application. Ignoring the proper order leads to runtime errors and performance issues. Let's look at the complete chain, focusing on the most critical distinctions.

Lifecycle Sequence Breakdown (The 11 Steps)

Step Hook Timing and Purpose Code Example Use Case
1 ngOnChanges First Run & Input Update. Called whenever a new value is bound to an @Input(). if (changes['userId']) { this.loadNewUser(changes['userId'].currentValue); }
2 ngOnInit Initial Setup. Called once after the first ngOnChanges. this.data$ = this.service.fetchData();
3 ngDoCheck Custom Check. Runs after ngOnInit and then frequently. Use only for manually detecting deep changes not tracked by Angular. if (this.data.length !== this.previousLength) { /* update state */ }
4 ngAfterContentInit Content Projection Init. Runs once after external content (<ng-content>) is initialized. this.queryList.changes.subscribe(() => { /* setup projected content */ });
5 ngAfterContentChecked Content Check. Runs after ngAfterContentInit and after every check. Reacting to subtle changes within the projected content.
6 ngAfterViewInit View Render Init. Runs once after the component's template and its child views are fully initialized. The DOM is ready here. this.chartCanvas.nativeElement.getContext('2d').fillRect(...)
7 ngAfterViewChecked View Update Check. Runs after ngAfterViewInit and after every subsequent check. Reacting to view changes, often used to adjust state based on new DOM properties.
8-10 Repeat 3, 5, 7 Recurrence. The trio of ngDoCheck, ngAfterContentChecked, and ngAfterViewChecked runs repeatedly throughout the component's life as state changes. Avoid placing heavy logic here.
11 ngOnDestroy Cleanup. Called just before the component is removed. Non-Negotiable. this.subscription.unsubscribe();

The Critical Pitfall: View vs. Content

Many developers confuse ngAfterContentInit and ngAfterViewInit.

  • Content: What the parent component puts inside your tags (<app-child>**<p>My Content</p>**</app-child>). → Use ngAfterContent...
  • View: What your component defines in its own template (template: '<div>**<canvas>**</div>').→ Use ngAfterView...

The Cleanup Rule: Preventing Memory Leaks

If you don't explicitly stop a process, it keeps running in the background. ngOnDestroy is your shield against memory leaks.

// component.ts
import { Component, OnInit, OnDestroy, Subscription } from '@angular/core';

export class DashboardComponent implements OnInit, OnDestroy {
  private updateSubscription!: Subscription; // ! tells TypeScript it will be assigned

  ngOnInit() {
    // Start an observable stream that runs forever
    this.updateSubscription = this.apiService.getLiveUpdates().subscribe(data => {
      // process data
    });
  }

  // CRITICAL: Stop the stream when the component dies
  ngOnDestroy() {
    if (this.updateSubscription) {
      this.updateSubscription.unsubscribe();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

By respecting this 11-step lifecycle, you ensure your component adheres to Angular's unidirectional data flow, dramatically reducing the potential for runtime errors and improving application stability.

#Angular #TypeScript #WebDev #Coding #SoftwareEngineering #DevTo #DailyDev

Top comments (0)