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:

Learn More About Angular ๐Ÿš€

What is Angular vs AngularJS ๐Ÿ‘‰ Explained
Key Features of Angular ๐Ÿ‘‰ Explained
Angular Architecture ๐Ÿ‘‰ Explained
Components in Angular ๐Ÿ‘‰ Explained
Modules in Angular ๐Ÿ‘‰ Explained
Templates in Angular ๐Ÿ‘‰ Explained
Directives in Angular ๐Ÿ‘‰ Explained
Structural vs Attribute Directives ๐Ÿ‘‰ Explained
Services in Angular ๐Ÿ‘‰ Explained
Dependency Injection in Angular ๐Ÿ‘‰ Explained
Data Binding in Angular ๐Ÿ‘‰ Explained
Interpolation ๐Ÿ‘‰ Explained
Property Binding ๐Ÿ‘‰ Explained
Event Binding ๐Ÿ‘‰ Explained
Two-way Data Binding ๐Ÿ‘‰ Explained
ngModel Usage ๐Ÿ‘‰ Explained
Lifecycle Hooks ๐Ÿ‘‰ Explained
ngOnInit Hook ๐Ÿ‘‰ Explained
ngOnDestroy Hook ๐Ÿ‘‰ Explained
Pipes in Angular ๐Ÿ‘‰ Explained
Pure vs Impure Pipes ๐Ÿ‘‰ Explained
Create Custom Pipe ๐Ÿ‘‰ Explained
Angular Forms ๐Ÿ‘‰ Explained
Template-driven vs Reactive Forms ๐Ÿ‘‰ Explained
Form Controls ๐Ÿ‘‰ Explained
Form Validation ๐Ÿ‘‰ Explained
Validation Error Messages ๐Ÿ‘‰ Explained
FormGroup vs FormControl ๐Ÿ‘‰ Explained
Enable/Disable Form Fields ๐Ÿ‘‰ Explained
Reset Form ๐Ÿ‘‰ Explained
Routing in Angular ๐Ÿ‘‰ Explained
RouterModule ๐Ÿ‘‰ Explained
Configure Routes ๐Ÿ‘‰ Explained
Route Guards ๐Ÿ‘‰ Explained
CanActivate vs CanDeactivate ๐Ÿ‘‰ Explained
Lazy Loading ๐Ÿ‘‰ Explained
Preloading in Routing ๐Ÿ‘‰ Explained
Wildcard Routes ๐Ÿ‘‰ Explained
Route Parameters ๐Ÿ‘‰ Explained
Query Parameters ๐Ÿ‘‰ Explained
Programmatic Navigation ๐Ÿ‘‰ Explained
routerLink & routerLinkActive ๐Ÿ‘‰ Explained
Resolvers in Routing ๐Ÿ‘‰ Explained
Observables in Angular ๐Ÿ‘‰ Explained
RxJS in Angular ๐Ÿ‘‰ Explained
Observable vs Promise ๐Ÿ‘‰ Explained
Share:

Tags:


Feedback Modal Popup