Lifecycle Hooks
9 min read
Component Lifecycle
Every Angular component goes through a lifecycle: creation, change detection cycles, and eventual destruction. Angular provides lifecycle hook interfaces that let you tap into these moments to run initialization code, react to input changes, or clean up subscriptions.
ngOnChanges— called when@Input()properties change (beforengOnInit)ngOnInit— called once after the firstngOnChanges; ideal for data fetchingngDoCheck— called on every change detection run (use sparingly)ngAfterContentInit— called after<ng-content>is projectedngAfterViewInit— called after the component's view and child views are initializedngOnDestroy— called just before Angular destroys the component; clean up here
ts
import {
Component, OnInit, OnDestroy, OnChanges,
Input, SimpleChanges, inject
} from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from '../services/data.service';
@Component({
selector: 'app-lifecycle-demo',
standalone: true,
template: `<p>{{ title }}</p>`
})
export class LifecycleDemoComponent implements OnInit, OnDestroy, OnChanges {
@Input() userId = 0;
title = '';
private sub?: Subscription;
private dataService = inject(DataService);
ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) {
console.log('userId changed to', this.userId);
}
}
ngOnInit() {
this.sub = this.dataService.getTitle().subscribe(t => {
this.title = t;
});
}
ngOnDestroy() {
// Critical: prevent memory leaks
this.sub?.unsubscribe();
}
}Always unsubscribe from Observables in ngOnDestroy, or use Angular's takeUntilDestroyed() operator, to prevent memory leaks when components are removed from the DOM.
Ready to test yourself?
Practice Angular— quiz & coding exercises