0
0
AngularConceptBeginner · 3 min read

What is ngOnDestroy in Angular: Lifecycle Hook Explained

ngOnDestroy is a lifecycle hook in Angular that runs just before a component or directive is removed from the screen. It lets you clean up resources like subscriptions or timers to avoid memory leaks.
⚙️

How It Works

Think of ngOnDestroy as a cleanup crew that arrives right before a component leaves the stage. When Angular removes a component or directive from the view, it calls ngOnDestroy to give you a chance to tidy up.

This cleanup is important because components often create things like timers, event listeners, or data subscriptions that keep running in the background. If you don’t stop them, they can waste memory or cause bugs.

Using ngOnDestroy is like turning off the lights and locking the doors when you leave a room. It helps keep your app fast and error-free.

đź’»

Example

This example shows a component that starts a timer when it loads and stops it when the component is destroyed using ngOnDestroy.

typescript
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, interval } from 'rxjs';

@Component({
  selector: 'app-timer',
  template: `<p>Seconds passed: {{seconds}}</p>`
})
export class TimerComponent implements OnInit, OnDestroy {
  seconds = 0;
  private timerSubscription: Subscription | null = null;

  ngOnInit() {
    // Start a timer that updates every second
    this.timerSubscription = interval(1000).subscribe(() => {
      this.seconds++;
    });
  }

  ngOnDestroy() {
    // Stop the timer to prevent memory leaks
    if (this.timerSubscription) {
      this.timerSubscription.unsubscribe();
      console.log('Timer stopped in ngOnDestroy');
    }
  }
}
Output
Seconds passed: 0 Seconds passed: 1 Seconds passed: 2 ... (increments every second until component is destroyed) Timer stopped in ngOnDestroy
🎯

When to Use

Use ngOnDestroy whenever your component or directive creates something that needs to be cleaned up. Common cases include:

  • Unsubscribing from data streams or event listeners
  • Clearing timers or intervals
  • Releasing resources like WebSocket connections

This prevents your app from slowing down or crashing due to leftover processes running after the component is gone.

âś…

Key Points

  • ngOnDestroy runs just before Angular removes a component or directive.
  • It is used to clean up resources like subscriptions and timers.
  • Helps prevent memory leaks and unexpected behavior.
  • Always implement it when your component sets up ongoing processes.
âś…

Key Takeaways

ngOnDestroy is a lifecycle hook called before a component is destroyed.
Use ngOnDestroy to clean up subscriptions, timers, and other resources.
Cleaning up prevents memory leaks and keeps your app efficient.
Always implement ngOnDestroy when your component starts ongoing processes.