Advertisement
Intermediate Angular, Lifecycle Hooks

What does ngOnDestroy do, and why is it important for cleaning up resources like subscriptions?

Short answer

ngOnDestroy runs right before Angular removes a component from the page, giving you a chance to clean up anything that would otherwise keep running unnecessarily, such as unsubscribing from an observable or clearing a timer, preventing memory leaks in a long running application.

Save Angular mock interview
Advertisement
AModel answer
ngOnDestroy runs right before Angular removes a component from the page, giving you a chance to clean up anything that would otherwise keep running unnecessarily, such as unsubscribing from an observable or clearing a timer, preventing memory leaks in a long running application.
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

export class TimerComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    this.subscription = interval(1000).subscribe(() => console.log('tick'));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
Real-world example
A live clock component correctly stops its timer when the user navigates away from the page, because it unsubscribes inside ngOnDestroy, avoiding a hidden timer that keeps running forever in the background.
Likely follow-ups
  • What happens if you forget to unsubscribe from an observable inside ngOnDestroy?
  • How does the async pipe help avoid needing to manually unsubscribe in many cases?
Related topics