Bird
Raised Fist0
Angularframework~10 mins

ngOnDestroy for cleanup in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - ngOnDestroy for cleanup
Component Initialized
↓
Component Renders
↓
Component in Use
↓
Component Destroy Triggered
↓
ngOnDestroy Called
↓
Cleanup Tasks Executed
↓
Component Removed from DOM
This flow shows how Angular calls ngOnDestroy when a component is about to be removed, allowing cleanup like unsubscribing or stopping timers.
Execution Sample
Angular
import { Component, OnDestroy } from '@angular/core';

@Component({ selector: 'app-demo', template: '<p>Demo</p>' })
export class DemoComponent implements OnDestroy {
  intervalId = setInterval(() => console.log('tick'), 1000);
  ngOnDestroy() {
    clearInterval(this.intervalId);
  }
}
This component starts a timer on creation and stops it in ngOnDestroy when the component is removed.
Execution Table
StepActionState BeforeState AfterEffect
1Component createdintervalId: undefinedintervalId: timer runningTimer starts logging 'tick' every second
2Component in useintervalId: timer runningintervalId: timer runningTimer continues running
3Component removal triggeredintervalId: timer runningintervalId: timer runningPreparing to destroy component
4ngOnDestroy calledintervalId: timer runningintervalId: clearedTimer stopped, no more 'tick' logs
5Component removedintervalId: clearedComponent goneCleanup complete, no memory leaks
💡 Component is removed, ngOnDestroy cleanup stops the timer to prevent resource leaks
Variable Tracker
VariableStartAfter Step 1After Step 4Final
intervalIdundefinedtimer runningclearedcleared
Key Moments - 3 Insights
Why do we clear the interval in ngOnDestroy?
Because the timer keeps running even after the component is removed, causing memory leaks or unwanted behavior. The execution_table row 4 shows ngOnDestroy stopping the timer.
When exactly is ngOnDestroy called?
It is called right before Angular removes the component from the DOM, as shown in execution_table step 4.
What happens if we don't implement ngOnDestroy for cleanup?
Resources like timers or subscriptions keep running, which can slow down the app or cause bugs. The execution_table shows the timer running before cleanup and stopping after ngOnDestroy.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of intervalId after step 1?
AUndefined
BTimer cleared
CTimer running
DComponent removed
💡 Hint
Check the 'State After' column in row 1 of execution_table
At which step does ngOnDestroy stop the timer?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look for 'ngOnDestroy called' in the 'Action' column in execution_table
If we remove the clearInterval call, what would happen to intervalId after component removal?
AIt would be cleared automatically
BIt would keep running causing memory leaks
CIt would throw an error
DIt would stop after some time
💡 Hint
Refer to key_moments explanation about cleanup necessity
Concept Snapshot
ngOnDestroy is a lifecycle hook Angular calls before removing a component.
Use it to clean up resources like timers or subscriptions.
Without cleanup, resources keep running causing memory leaks.
Implement ngOnDestroy() method and perform cleanup inside.
Angular calls it automatically when component is destroyed.
Full Transcript
In Angular, ngOnDestroy is a special method called when a component is about to be removed from the screen. This is the perfect time to stop timers, unsubscribe from data streams, or clean any resources to keep the app healthy. For example, if a component starts a timer, it keeps running even if the component is gone, unless we stop it in ngOnDestroy. The flow starts with component creation, then usage, then removal triggers ngOnDestroy, which runs cleanup code, and finally the component is removed. The execution table shows the timer starting, running, and stopping exactly when ngOnDestroy runs. Tracking the intervalId variable shows it changes from running to cleared. Beginners often wonder why cleanup is needed or when ngOnDestroy runs; it always runs just before removal. If cleanup is skipped, timers or subscriptions keep running, causing bugs or slowdowns. The quiz questions help check understanding of these steps and states.

Practice

(1/5)
1. What is the main purpose of the ngOnDestroy lifecycle hook in Angular?
easy
A. To handle user input events
B. To initialize component data when it is created
C. To run cleanup code when a component or directive is removed
D. To render the component template

Solution

  1. Step 1: Understand the role of ngOnDestroy

    The ngOnDestroy hook is called when Angular removes a component or directive from the view.
  2. Step 2: Identify its main use

    It is used to clean up resources like timers, subscriptions, or event listeners to avoid memory leaks.
  3. Final Answer:

    To run cleanup code when a component or directive is removed -> Option C
  4. Quick Check:

    ngOnDestroy = cleanup [OK]
Hint: Remember: ngOnDestroy cleans up before component removal [OK]
Common Mistakes:
  • Confusing ngOnDestroy with ngOnInit
  • Thinking it initializes data
  • Assuming it handles user events
2. Which of the following is the correct way to implement ngOnDestroy in an Angular component?
easy
A. destroy() { console.log('Component destroyed'); }
B. ngOnDestroy = () => { console.log('Component destroyed'); }
C. function ngOnDestroy() { console.log('Component destroyed'); }
D. ngOnDestroy() { console.log('Component destroyed'); }

Solution

  1. Step 1: Recall Angular lifecycle hook syntax

    Angular lifecycle hooks are methods inside the component class with exact names like ngOnDestroy().
  2. Step 2: Check method declaration style

    The correct syntax is a method, not an arrow function or standalone function, and must be named exactly ngOnDestroy.
  3. Final Answer:

    ngOnDestroy() { console.log('Component destroyed'); } -> Option D
  4. Quick Check:

    ngOnDestroy method syntax = ngOnDestroy() { console.log('Component destroyed'); } [OK]
Hint: Use method syntax named exactly ngOnDestroy [OK]
Common Mistakes:
  • Using arrow functions for lifecycle hooks
  • Naming method incorrectly
  • Defining lifecycle hook outside class
3. Consider this Angular component code snippet:
export class TimerComponent implements OnDestroy {
  intervalId = setInterval(() => console.log('tick'), 1000);

  ngOnDestroy() {
    clearInterval(this.intervalId);
    console.log('Timer stopped');
  }
}

What will happen when this component is removed from the view?
medium
A. The interval stops and logs 'Timer stopped' once
B. An error occurs because clearInterval is not valid here
C. Nothing happens because ngOnDestroy is not called automatically
D. The interval keeps running and logs 'tick' every second

Solution

  1. Step 1: Understand what ngOnDestroy does here

    When the component is removed, Angular calls ngOnDestroy, which clears the interval timer.
  2. Step 2: Effect of clearing the interval

    Clearing the interval stops the repeated 'tick' logs, and the message 'Timer stopped' is logged once.
  3. Final Answer:

    The interval stops and logs 'Timer stopped' once -> Option A
  4. Quick Check:

    ngOnDestroy clears timer = The interval stops and logs 'Timer stopped' once [OK]
Hint: ngOnDestroy stops timers to prevent leaks [OK]
Common Mistakes:
  • Thinking interval keeps running after destroy
  • Assuming ngOnDestroy is not called
  • Confusing clearInterval usage
4. You have this Angular component:
export class DataComponent implements OnDestroy {
  subscription = this.dataService.getData().subscribe();

  ngOnDestroy() {
    this.subscription.unsubscribe;
  }
}

What is the problem with this code?
medium
A. The unsubscribe method is not called correctly
B. The subscription is never created
C. ngOnDestroy is missing the return type
D. There is no problem; code works fine

Solution

  1. Step 1: Check how unsubscribe is used

    The code uses this.subscription.unsubscribe; without parentheses, so the method is not actually called.
  2. Step 2: Correct usage of unsubscribe

    It should be this.subscription.unsubscribe(); to properly stop the subscription and avoid memory leaks.
  3. Final Answer:

    The unsubscribe method is not called correctly -> Option A
  4. Quick Check:

    Call unsubscribe() with parentheses [OK]
Hint: Always call unsubscribe() as a function [OK]
Common Mistakes:
  • Forgetting parentheses on unsubscribe
  • Assuming unsubscribe is a property
  • Ignoring ngOnDestroy lifecycle
5. You have a component that subscribes to multiple observables and sets up an event listener:
export class MultiCleanupComponent implements OnDestroy {
  sub1 = this.service1.getData().subscribe();
  sub2 = this.service2.getData().subscribe();

  constructor() {
    window.addEventListener('resize', this.onResize);
  }

  onResize() {
    console.log('Window resized');
  }

  ngOnDestroy() {
    // What should be done here?
  }
}

Which is the best way to clean up all resources in ngOnDestroy?
hard
A. Only call this.sub1.unsubscribe(); this.sub2.unsubscribe();
B. Call this.sub1.unsubscribe(); this.sub2.unsubscribe(); window.removeEventListener('resize', this.onResize);
C. Only call window.removeEventListener('resize', this.onResize);
D. No cleanup needed because Angular handles it automatically

Solution

  1. Step 1: Identify all resources to clean

    The component has two subscriptions and an event listener on the window.
  2. Step 2: Proper cleanup in ngOnDestroy

    To avoid memory leaks, unsubscribe both subscriptions and remove the event listener using removeEventListener.
  3. Final Answer:

    Call this.sub1.unsubscribe(); this.sub2.unsubscribe(); window.removeEventListener('resize', this.onResize); -> Option B
  4. Quick Check:

    Unsubscribe and remove listeners in ngOnDestroy [OK]
Hint: Clean all subscriptions and listeners in ngOnDestroy [OK]
Common Mistakes:
  • Forgetting to remove event listeners
  • Only unsubscribing some observables
  • Assuming Angular cleans up automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard