Component Lifecycle Hooks
Lifecycle hooks special methods hain jo Angular AUTOMATICALLY call karta hai component ki lifetime ke specific MOMENTS par. ngOnInit (component initialize hone ke baad — data fetching yahi karo, constructor mein nahi). ngOnChanges (@Input value change hone par). ngOnDestroy (component remove hone se PEHLE — cleanup, subscriptions unsubscribe karne ke liye zaroori).
import { Component, OnInit, OnDestroy } from '@angular/core';
export class UserProfileComponent implements OnInit, OnDestroy {
constructor() {
console.log('Constructor — object ban raha hai');
}
ngOnInit() {
console.log('ngOnInit — component ready hai, data fetch karo yahan');
// API calls, initial setup yahi karo
}
ngOnDestroy() {
console.log('ngOnDestroy — cleanup karo, subscriptions unsubscribe karo');
// memory leaks avoid karne ke liye zaroori
}
}- ngOnInit = component ready hai — data fetching yahan karo
- ngOnDestroy = cleanup, memory leaks avoid karne ke liye zaroori
- constructor sirf basic setup ke liye, business logic ke liye nahi
Angular components ke paas 8 lifecycle hooks hain, ek SPECIFIC order mein chalते hain: constructor → ngOnChanges → ngOnInit → ngDoCheck → ngAfterContentInit → ngAfterContentChecked → ngAfterViewInit → ngAfterViewChecked → (repeat DoCheck/AfterContentChecked/AfterViewChecked on updates) → ngOnDestroy.
export class DemoComponent implements OnInit, AfterViewInit {
constructor() { console.log('1. constructor'); }
ngOnChanges() { console.log('2. ngOnChanges (agar @Input hai)'); }
ngOnInit() { console.log('3. ngOnInit'); }
ngAfterViewInit() { console.log('4. ngAfterViewInit — view fully ready'); }
ngOnDestroy() { console.log('LAST. ngOnDestroy'); }
}ngAfterViewInit tab chalता hai jab component ka VIEW (aur uske child components) poori tarah initialize ho chuke hon — @ViewChild se DOM elements/child components access karne ke liye yehi sahi jagah hai, ngOnInit mein nahi (tab tak view ready nahi hoti).
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
export class SearchComponent implements AfterViewInit {
@ViewChild('searchInput') inputRef!: ElementRef;
ngAfterViewInit() {
this.inputRef.nativeElement.focus(); // ab element guaranteed exist karta hai
}
}
// Template: <input #searchInput type="text">