Angular Component Lifecycle Hooks Explained
Estimated study time: 9 minutes. A closer, example-driven look at each hook and when to reach for it.
Building on the basics, let's go through each Angular lifecycle hook individually with a concrete use case for when you'd actually reach for it.
ngOnChanges(changes: SimpleChanges)
Fires whenever a bound @Input() value changes, before ngOnInit and on every subsequent update. Useful when a child component needs to react specifically to an input changing.
ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) {
this.loadUserData(changes['userId'].currentValue);
}
}
ngOnInit()
The most commonly used hook — runs once after the component's inputs are set. This is where you typically fetch initial data or set up subscriptions.
ngOnInit() {
this.subscription = this.dataService.currentMessage$.subscribe(
msg => this.message = msg
);
}
ngDoCheck()
Runs on every change detection cycle, giving you a hook into Angular's default change detection when you need to catch changes it wouldn't detect automatically (like mutations inside an object or array).
ngAfterContentInit() / ngAfterContentChecked()
Relevant when a component projects content via <ng-content>. ngAfterContentInit runs once the projected content has been initialized — useful for reading a @ContentChild reference.
ngAfterViewInit() / ngAfterViewChecked()
Runs after the component's own view (and child views) have been fully initialized. This is the right place to interact with the DOM directly or read a @ViewChild reference.
@ViewChild('chartCanvas') canvasRef!: ElementRef;
ngAfterViewInit() {
this.renderChart(this.canvasRef.nativeElement);
}
ngOnDestroy()
Called right before Angular removes the component. Always unsubscribe from observables, clear intervals, and remove manually-added event listeners here to prevent memory leaks.
ngOnDestroy() {
this.subscription.unsubscribe();
}