Bird
Raised Fist0
Angularframework~10 mins

ngOnDestroy for cleanup in Angular - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to implement the Angular lifecycle hook for cleanup.

Angular
import { Component, [1] } from '@angular/core';

@Component({
  selector: 'app-sample',
  template: `<p>Sample component</p>`
})
export class SampleComponent implements [1] {
  ngOnDestroy() {
    console.log('Cleanup done');
  }
}
Drag options to blanks, or click blank then click option'
ADoCheck
BAfterViewInit
COnInit
DOnDestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Using OnInit instead of OnDestroy
Forgetting to implement the interface
Misspelling ngOnDestroy
2fill in blank
medium

Complete the code to unsubscribe from a subscription in ngOnDestroy.

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

@Component({
  selector: 'app-timer',
  template: `<p>Timer running</p>`
})
export class TimerComponent implements OnDestroy {
  private timerSub: Subscription;

  constructor() {
    this.timerSub = new Subscription();
  }

  ngOnDestroy() {
    this.timerSub.[1]();
  }
}
Drag options to blanks, or click blank then click option'
Aunsubscribe
Bclose
Cstop
Ddestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a non-existent method like stop or destroy
Forgetting to unsubscribe
Calling unsubscribe outside ngOnDestroy
3fill in blank
hard

Fix the error in the ngOnDestroy method to properly clean up a timer.

Angular
export class ClockComponent implements OnDestroy {
  private intervalId: any;

  start() {
    this.intervalId = setInterval(() => {
      console.log('Tick');
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval([1]);
  }
}
Drag options to blanks, or click blank then click option'
Athis.setInterval
Bthis.intervalId
CsetInterval
DintervalId
Attempts:
3 left
💡 Hint
Common Mistakes
Using the variable name without this
Passing the function instead of the ID
Using a wrong property name
4fill in blank
hard

Fill both blanks to correctly implement ngOnDestroy and clean up a subscription.

Angular
import { Component, [1] } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-data',
  template: `<p>Data loaded</p>`
})
export class DataComponent implements [1] {
  private dataSub: Subscription = new Subscription();

  ngOnDestroy() {
    this.dataSub.[2]();
  }
}
Drag options to blanks, or click blank then click option'
AOnDestroy
BOnInit
Cunsubscribe
Ddestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Implementing wrong lifecycle interface
Calling a non-existent method like destroy
Not unsubscribing in ngOnDestroy
5fill in blank
hard

Fill all three blanks to correctly clean up multiple subscriptions in ngOnDestroy.

Angular
import { Component, [1] } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-multi',
  template: `<p>Multiple subscriptions</p>`
})
export class MultiSubComponent implements [1] {
  private sub1: Subscription = new Subscription();
  private sub2: Subscription = new Subscription();

  ngOnDestroy() {
    this.sub1.[2]();
    this.sub2.[3]();
  }
}
Drag options to blanks, or click blank then click option'
AOnDestroy
Bunsubscribe
Cdestroy
DOnInit
Attempts:
3 left
💡 Hint
Common Mistakes
Using destroy instead of unsubscribe
Not implementing OnDestroy
Unsubscribing only one subscription

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