What is the purpose of ngOnDestroy in Angular?

๐Ÿ’ก Concept Name

ngOnDestroy is a lifecycle hook in Angular used to perform cleanup operations like unsubscribing from observables, detaching event handlers, or clearing timers before a component or directive is destroyed.

๐Ÿ“œ Quick Intro

When a component is removed from the DOM, Angular calls ngOnDestroy(). It's your chance to clean up memory-leaking resources like subscriptions, custom services, or any ongoing tasks the component started.

๐Ÿง  Analogy / Short Story

Imagine finishing a camping trip. Before leaving, you put out the fire, pack your tent, and dispose of trash. Similarly, ngOnDestroy ensures you clean up everything before a component leaves.

๐Ÿ”ง Technical Explanation

  • ๐Ÿ”น Called right before Angular destroys the component or directive instance.
  • ๐Ÿ”น Used for unsubscribing from RxJS subscriptions.
  • ๐Ÿ”น Clears timers or intervals to prevent leaks.
  • ๐Ÿ”น Detaches event listeners or removes DOM nodes manually added.
  • ๐Ÿ”น Helps avoid memory leaks in long-running SPAs.

๐ŸŽฏ Purpose & Use Case

  • โœ… Cleanup subscriptions from observables.
  • โœ… Remove global event listeners (e.g., window resize).
  • โœ… Stop background timers or intervals.
  • โœ… Clear dynamically created DOM elements.

๐Ÿ’ป Real Code Example

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

                    @Component({
                        selector: 'app-timer',
  template: '<p>Check the console for timer output</p>'
                        })
export class TimerComponent implements OnDestroy {

  private subscription: Subscription;

  constructor() {
    this.subscription = interval(1000).subscribe(val => console.log('Tick:', val));
  }

  ngOnDestroy() {
    console.log('Component destroyed. Cleaning up...');
    this.subscription.unsubscribe();
  }
}

โ“ Interview Q&A

Q1: What does ngOnDestroy do?
A: It performs cleanup operations before a component is destroyed.

Q2: Why is it important to unsubscribe in ngOnDestroy?
A: To avoid memory leaks and ensure efficient resource use.

Q3: Can you access component properties in ngOnDestroy?
A: Yes, you can access instance variables for cleanup.

Q4: Is ngOnDestroy called automatically?
A: Yes, by Angular when the component is destroyed.

Q5: What happens if you forget to unsubscribe?
A: Observables continue running and may cause memory leaks.

๐Ÿ’ก Bonus Insight

For managing multiple subscriptions, use a Subject with takeUntil() in combination with ngOnDestroy for a cleaner teardown pattern in Angular components.

๐Ÿ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

โžก๏ธ Next:

๐Ÿ’ฌ Feedback
๐Ÿš€ Start Learning
Share:

Tags: