0
0
Angularframework~5 mins

ngOnDestroy for cleanup in Angular

Choose your learning style9 modes available
Introduction

ngOnDestroy helps you clean up when a component or directive is removed. It stops memory leaks and unwanted tasks.

You want to stop a timer or interval when a component is gone.
You need to unsubscribe from data streams to avoid memory leaks.
You want to remove event listeners added manually.
You want to clear resources or reset states when leaving a page.
Syntax
Angular
import { OnDestroy } from '@angular/core';

export class MyComponent implements OnDestroy {
  ngOnDestroy() {
    // cleanup code here
  }
}

ngOnDestroy is a lifecycle method Angular calls automatically before destroying the component.

Implement the OnDestroy interface to get type checking and clarity.

Examples
This example stops a timer when the component is destroyed to avoid it running forever.
Angular
import { OnDestroy } from '@angular/core';

export class TimerComponent implements OnDestroy {
  intervalId: any;

  startTimer() {
    this.intervalId = setInterval(() => {
      console.log('Tick');
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
  }
}
This example unsubscribes from an observable to prevent memory leaks when the component is removed.
Angular
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

export class DataComponent implements OnDestroy {
  dataSub: Subscription;

  ngOnInit() {
    this.dataSub = someObservable.subscribe(data => {
      console.log(data);
    });
  }

  ngOnDestroy() {
    this.dataSub.unsubscribe();
  }
}
Sample Program

This component starts a timer that logs a message every second. When the component is destroyed, ngOnDestroy stops the timer and logs a final message.

Angular
import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-cleanup-example',
  template: `<p>Check the console for timer messages.</p>`
})
export class CleanupExampleComponent implements OnDestroy {
  intervalId: any;

  constructor() {
    this.intervalId = setInterval(() => {
      console.log('Timer running...');
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
    console.log('Timer stopped on destroy');
  }
}
OutputSuccess
Important Notes

Always clean up subscriptions and timers in ngOnDestroy to keep your app fast and bug-free.

If you forget cleanup, your app might slow down or behave strangely over time.

Summary

ngOnDestroy runs cleanup code when a component or directive is removed.

Use it to stop timers, unsubscribe from observables, and remove event listeners.

This helps prevent memory leaks and keeps your app healthy.