Lesson 22 / 30
ngOnInit, ngOnDestroy & ngOnChanges
Hook into key moments of a component's life.
Why hooks exist
Angular calls specific methods at specific moments — creation, updates, destruction — if your class implements them. This is how you run setup and cleanup code at the right time.
ngOnInit & ngOnDestroy
ngOnInit runs once after the component's inputs are first set — the usual place to fetch initial data. ngOnDestroy runs right before the component is removed — clean up subscriptions and timers there.
export class TimerComponent implements OnInit, OnDestroy {
private intervalId?: ReturnType<typeof setInterval>;
ngOnInit() {
this.intervalId = setInterval(() => this.tick(), 1000);
}
ngOnDestroy() {
clearInterval(this.intervalId);
}
tick() { /* ... */ }
}ngOnChanges
ngOnChanges fires whenever a bound @Input() value changes, receiving both the previous and current values.
ngOnChanges(changes: SimpleChanges) {
if (changes['rating']) {
console.log(changes['rating'].previousValue, changes['rating'].currentValue);
}
}Quick check: Where should you clear a timer or unsubscribe from a stream?
- ngOnInit
- ngOnChanges
- ngOnDestroy
Answer
ngOnDestroy — ngOnDestroy runs right before the component is removed — the correct place for cleanup.