Angular calls lifecycle hook methods at specific moments in a component's life — from creation through destruction.
import {
Component, OnInit, OnChanges, OnDestroy,
AfterViewInit, AfterContentInit,
Input, SimpleChanges
} from '@angular/core';
@Component({ selector: 'app-demo', standalone: true, template: '...' })
export class DemoComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@Input() userId!: number;
// Called before ngOnInit, every time an @Input changes
ngOnChanges(changes: SimpleChanges): void {
if (changes['userId']) {
const { previousValue, currentValue } = changes['userId'];
console.log(`userId changed: ${previousValue} → ${currentValue}`);
this.loadUser(currentValue);
}
}
// Called once after first ngOnChanges — initialise logic here
ngOnInit(): void {
console.log('Component initialised');
}
// Called after Angular initialises the component's view
ngAfterViewInit(): void {
console.log('View ready — safe to access @ViewChild refs');
}
// Called just before Angular destroys the component
ngOnDestroy(): void {
console.log('Cleanup — unsubscribe, clear timers');
this.subscription?.unsubscribe();
}
}
| Hook | When | Use For |
|---|---|---|
| ngOnInit | After first render | Fetch data, setup |
| ngOnChanges | On @Input change | React to prop changes |
| ngAfterViewInit | After view renders | Access DOM, @ViewChild |
| ngOnDestroy | Before destruction | Cleanup, unsubscribe |