Complete the code to implement the Angular lifecycle hook for cleanup.
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'); } }
The OnDestroy interface is used to implement the ngOnDestroy lifecycle hook for cleanup in Angular components.
Complete the code to unsubscribe from a subscription in ngOnDestroy.
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](); } }
To clean up subscriptions in Angular, call unsubscribe() inside ngOnDestroy().
Fix the error in the ngOnDestroy method to properly clean up a timer.
export class ClockComponent implements OnDestroy { private intervalId: any; start() { this.intervalId = setInterval(() => { console.log('Tick'); }, 1000); } ngOnDestroy() { clearInterval([1]); } }
Use this.intervalId to clear the interval set in the component.
Fill both blanks to correctly implement ngOnDestroy and clean up a subscription.
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](); } }
The component must implement OnDestroy and call unsubscribe() on the subscription in ngOnDestroy().
Fill all three blanks to correctly clean up multiple subscriptions in ngOnDestroy.
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](); } }
Implement OnDestroy and call unsubscribe() on both subscriptions to clean up properly.