Angular Life Cycle Hooks
Angular Life Cycle Hooks
Angular provides a set oflifecycle hooksthat let you tap into different phases of a
A
component or directive’s life — from creation to destruction. Understanding these hooks is
essentialfor building scalable, performant, and bug-freeAngular apps — especially at 6+ years
of experience level.
🔄
Angular Lifecycle Hooks (With Use Cases & Execution
Order)
🔹 1.
ngOnChanges(changes: SimpleChanges)
@Input()data.
● Use Case: Detect changes to
ngOnChanges(changes: SimpleChanges) {
console.log('Input property changed:', changes);
}
🔹 2.
ngOnInit()
ngOnChanges()
● Purpose: Called once after the first .
ngOnInit() {
this.loadUserProfile();
}
🔹 3.
ngDoCheck()
@Input()hasn’t changed.
● Purpose: Calledon every change detection run, evenif
● U
se Case: Custom change detection (not recommended for frequent use unless
needed).
ngDoCheck() {
console.log('Change detection triggered!');
}
🔹 4.
ngAfterContentInit()
ngAfterContentInit() {
console.log('Content initialized');
}
🔹 5.
ngAfterContentChecked()
ngAfterContentChecked() {
console.log('Content checked');
}
🔹 6.
ngAfterViewInit()
● Purpose: Called once the component’s view (and childviews) are initialized.
@ViewChild()ortrigger animations.
● Use Case: Interact with DOM using
🔹 7.
ngAfterViewChecked()
● Purpose: Called after every check of the component’sview and its children.
ngAfterViewChecked() {
console.log('View checked');
}
🔹 8.
ngOnDestroy()
ngOnDestroy() {
this.subscription.unsubscribe();
}
ngOnChanges()
@Input()changes
Detect
ngOnInit()
Fetch API data, init form, subscriptions
ngDoCheck()
Custom dirty-checking logic
ngAfterViewInit( A
ViewChild
ccess DOM with ,
)
animations
ngOnDestroy()
leanup subscriptions, intervals,
C
services