When we are working with Angular 17+ then two important lifecycle hooks you will frequently use are ngOnInit and ngOnDestroy.
What are Angular Lifecycle Hooks?
Angular components go through a series of stages from when it’s created until it’s destroyed. These stages are known as lifecycle hooks.
Two of the most commonly used hooks are:
- ngOnInit – When the component is initialized.
- ngOnDestroy – When the component is destroyed.
What is ngOnInit?
ngOnInit() is a lifecycle hook that executes after Angular initializes the component and sets all input properties.
When does ngOnInit run?
I will explain it through the steps:
- Runs once, after the component is created.
- Runs after the constructor.
- Runs after all @Input() bindings are set.
Example for ngOnInit:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
standalone: true,
template: `{{ message }}
`
})
export class UserComponent implements OnInit {
message = '';
ngOnInit() {
this.message = 'Component Initialized!';
console.log('ngOnInit called');
}
}
What is ngOnDestroy?
ngOnDestroy() is a lifecycle hook that executes just before Angular destroys the component.
When does ngOnDestroy run?
Runs once, right before the component is removed from the DOM.
Example of ngOnDestroy
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-timer',
template: `Timer Running...
`
})
export class TimerComponent implements OnDestroy {
intervalId: any;
constructor() {
this.intervalId = setInterval(() => {
console.log('Timer running...');
}, 1000);
}
ngOnDestroy() {
clearInterval(this.intervalId);
console.log('ngOnDestroy called. Timer stopped.');
}
}
Difference Between ngOnInit vs ngOnDestroy
| Feature | ngOnInit | ngOnDestroy |
|---|---|---|
| Purpose | Initialization logic | Cleanup logic |
| Execution Time | After component creation | Before component destruction |
| Runs | Once | Once |
| Best For | API calls, subscriptions, default values | Unsubscribe, clear timers, remove listeners |
| Access @Input()? | ✔ Yes | ❌ No need |
| Recommended? | ✔ Yes | ✔ Yes (prevents memory leaks) |