Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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);
                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 1, 2019 at 7:33

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();
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.