Every Angular component has a strict lifecycle managed entirely by the framework.
Angular creates the component, renders it, checks for data changes, and eventually destroys it.
Lifecycle hooks allow you to tap into these specific moments and execute custom code.
Lifecycle hooks are simply methods that you define in your TypeScript component class.
Angular automatically looks for these specific method names and calls them at the right time.
To use them properly, your class should implement the corresponding interface from @angular/core.
The ngOnInit hook is the most commonly used lifecycle hook in Angular.
It is called exactly once, right after Angular has initialized all data-bound properties.
This makes it the perfect place to fetch initial data from an API or set up your component state!
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dashboard',
template: '<p>Dashboard loaded!</p>'
})
export class DashboardComponent implements OnInit {
// The constructor should only be used for dependency injection
constructor(private apiService: ApiService) {}
// ngOnInit is used for actual initialization logic
ngOnInit() {
console.log('Component initialized! Fetching data...');
// this.apiService.getData().subscribe(...);
}
}
The ngOnDestroy hook is called right before Angular destroys the component and removes it from the DOM.
This is the critical place to perform cleanup operations.
If you have custom event listeners, active intervals, or open RxJS subscriptions, you must unsubscribe here to prevent massive memory leaks!
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-timer',
template: '<p>Timer is running...</p>'
})
export class TimerComponent implements OnDestroy {
timerId = setInterval(() => console.log('Tick'), 1000);
ngOnDestroy() {
// We MUST clear the interval when the component is destroyed!
clearInterval(this.timerId);
console.log('Component destroyed, timer cleared.');
}
}
ngOnChanges: Called whenever a data-bound input property (@Input) changes.ngAfterViewInit: Called after Angular has fully initialized the component's views and child views. Perfect for direct DOM manipulation.ngDoCheck: Called during every change detection run, allowing you to implement custom change detection logic.Which lifecycle hook is the recommended place to perform initial data fetching requests?
What is the primary purpose of the ngOnDestroy hook?