Bird
0
0

Given this Angular component code, what will happen when the component is destroyed?

medium📝 component behavior Q4 of 15
Angular - Lifecycle Hooks
Given this Angular component code, what will happen when the component is destroyed?
export class SampleComponent implements OnDestroy {
  private timerId: any;
  constructor() {
    this.timerId = setInterval(() => console.log('tick'), 1000);
  }
  ngOnDestroy(): void {
    clearInterval(this.timerId);
    console.log('Timer cleared');
  }
}
AThe timer stops and 'Timer cleared' is logged once
BThe timer continues running and 'Timer cleared' is never logged
CAn error occurs because clearInterval is not called correctly
DThe timer stops but 'Timer cleared' is not logged
Step-by-Step Solution
Solution:
  1. Step 1: Analyze timer setup in constructor

    The component sets a repeating timer with setInterval that logs 'tick' every second.
  2. Step 2: Understand ngOnDestroy cleanup

    ngOnDestroy calls clearInterval with the stored timerId and logs 'Timer cleared'. This stops the timer and logs the message.
  3. Final Answer:

    The timer stops and 'Timer cleared' is logged once -> Option A
  4. Quick Check:

    ngOnDestroy clears timer and logs message = The timer stops and 'Timer cleared' is logged once [OK]
Quick Trick: Always clear timers in ngOnDestroy to stop them [OK]
Common Mistakes:
  • Not clearing the timer causing it to run indefinitely
  • Logging message outside ngOnDestroy
  • Using wrong method to clear timer

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes