I've seen a lot of question related to ngOnDestroy. I think many of us not using it correctly or not using it at all.
I just want to see a list of tips how can you properly use ngOnDestroy and what should we do in the best scenario to prevent memory leaks, speed up and optimize web apps.
What do you must to do in every case when you use it?(What are the steps you MUST to take?)
How far you need to go if you want to do it perfectly? Nullifying all references etc.
Asked
Active
Viewed 6,668 times
4

Jánosi-Borsos Róbert
- 500
- 6
- 17
2 Answers
4
The ngDestroy is called in a component’s lifecycle just before the instance of the component is finally destroyed. It is the perfect place to clean the component
import {OnDestroy } from '@angular/core'; // import from core
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy { // implements OnDestroy
//Call Constructor and set hello Msg.
constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
}
//Destroy to the component
ngOnDestroy() {
window.clearInterval(this.helloMsg);
}
}

Sneha Pawar
- 1,097
- 6
- 14
-
Nice example. Thank you. I'm familiar with this too. In my case i'm using dialog.closeall(), AmCharts.clear(), etc. – Jánosi-Borsos Róbert Feb 01 '19 at 07:33
3
One scenario where you are using Observable and subscribing it in a component and are getting a stream of data i.e Firebase. You should use ngOnDestroy and unsubscribe it when you leave the page to prevent the memory leak.
ngOnDestroy() {
this.data.unsubscribe();
}

Balaj Khan
- 2,490
- 2
- 17
- 30
-
1Yeah. I'm doing it but thanks for the answer. It may help the others. – Jánosi-Borsos Róbert Feb 01 '19 at 07:24