Directives, Pipes & Templates
Angular Lifecycle Hooks
Lifecycle hooks are methods Angular calls at defined moments in a component’s life — creation, input changes, view initialisation and destruction. Implementing them lets you run setup and teardown at exactly the right time.
What is Lifecycle Hooks in Angular?
Lifecycle hooks are methods Angular calls at defined moments in a component’s life — creation, input changes, view initialisation and destruction. Implementing them lets you run setup and teardown at exactly the right time.
Lifecycle Hooks example
export class JobListComponent implements OnInit, OnDestroy {
private sub?: Subscription;
ngOnInit(): void {
this.sub = this.api.getJobs().subscribe(jobs => (this.jobs = jobs));
}
ngOnDestroy(): void {
this.sub?.unsubscribe();
}
}Key points to remember
- Use the constructor only for dependency injection; put real work in ngOnInit.
- ngOnDestroy is where memory leaks are prevented — unsubscribe everything you subscribed manually.
- The async pipe removes most manual subscription management entirely.
The hooks in call order
| Hook | When it runs | Typical use |
|---|---|---|
| ngOnChanges | before ngOnInit and on every input change | react to a changed @Input |
| ngOnInit | once, after the first ngOnChanges | fetch data, set up subscriptions |
| ngDoCheck | every change detection cycle | custom change detection (rare) |
| ngAfterContentInit | after projected content is initialised | read @ContentChild |
| ngAfterViewInit | after the component’s view is initialised | read @ViewChild, focus, measure |
| ngOnDestroy | just before the component is destroyed | unsubscribe, clear timers |
Common mistakes with Lifecycle Hooks
- Fetching data in the constructor, which runs before inputs are available.
- Forgetting ngOnDestroy and leaking subscriptions each time the component is recreated.
Angular Lifecycle Hooks— Interview Questions & FAQs
What is the difference between the constructor and ngOnInit?+
The constructor runs when the class is instantiated, before Angular sets any @Input. ngOnInit runs after the first change detection pass, so inputs are populated — which is why data fetching belongs there.
