After covering ngOnChanges and ngOnInit earlier, let’s talk about ngOnDestroy. The ngOnDestroy
lifecycle hook is called when an Angular component/directive/pipe is destroyed. I’ll refer to components only in this post, but everything you read also applies to directives and pipes.
This can happen when the component is removed from the DOM, or the application is destroyed.
Most of the time, a component gets destroyed when it’s removed from the DOM as a result of:
- A
ngIf
directive condition becomesfalse
, thus hiding the element from the screen. - The router navigates to a different screen, thus removing the component from the DOM.
The ngOnDestroy
hook is a good place to do cleanup tasks, such as unsubscribing from Observables (though there are better options to automatically unsubscribe your Observables), closing sockets, or canceling setInterval
and setTimeout
tasks (though you could use RxJs timer for that):