Angular lifecycle hooks
Estimated study time: 7 minutes. Tapping into the key moments of a component's life, from creation to destruction.
Every Angular component goes through a predictable sequence of stages — created, rendered, updated, and eventually destroyed. Lifecycle hooks let you run code at each of these stages.
Why Lifecycle Hooks Matter
Without hooks, you'd have no reliable way to know when a component's inputs have changed, when its view is ready to be manipulated, or when it's about to be removed and needs to clean up subscriptions or timers.
The Core Hooks, In Order
- ngOnChanges — runs whenever an @Input() property changes.
- ngOnInit — runs once, after the first ngOnChanges; the standard place for initialization logic.
- ngDoCheck — runs on every change detection cycle, for custom change detection.
- ngAfterContentInit / ngAfterContentChecked — related to projected content (ng-content).
- ngAfterViewInit / ngAfterViewChecked — related to the component's own view and child views.
- ngOnDestroy — runs just before Angular destroys the component; the place to clean up.
A Basic Example
export class TimerComponent implements OnInit, OnDestroy {
private intervalId: any;
ngOnInit() {
this.intervalId = setInterval(() => console.log('tick'), 1000);
}
ngOnDestroy() {
clearInterval(this.intervalId);
}
}
💡 Tip: Always pair anything you start in ngOnInit (timers, subscriptions, listeners) with cleanup in ngOnDestroy — forgetting this is one of the most common sources of memory leaks in Angular apps.