Bird
0
0

You want to reset a component's internal counter to zero whenever the input resetFlag changes from false to true. Which ngOnChanges implementation correctly achieves this?

hard📝 lifecycle Q15 of 15
Angular - Lifecycle Hooks
You want to reset a component's internal counter to zero whenever the input resetFlag changes from false to true. Which ngOnChanges implementation correctly achieves this?
export class CounterComponent implements OnChanges {
  @Input() resetFlag = false;
  @Input() otherValue: number = 0;
  counter = 10;

  ngOnChanges(changes: SimpleChanges) {
    // Which option resets counter correctly?
  }
}
Aif (this.resetFlag) { this.counter = 0; }
Bif (changes['resetFlag'] && changes['resetFlag'].previousValue === true) { this.counter = 0; }
Cif (changes['resetFlag'].previousValue === false) { this.counter = 0; }
Dif (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; }
Step-by-Step Solution
Solution:
  1. Step 1: Detect resetFlag input change to true

    We must check if resetFlag changed and its new value is true.
  2. Step 2: Verify condition logic

    if (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; } checks both existence of change and currentValue === true, correctly resetting counter.
  3. Step 3: Analyze other options

    if (this.resetFlag) { this.counter = 0; } checks current value but runs on any input change, incorrectly resetting if resetFlag is true when other inputs change. if (changes['resetFlag'].previousValue === false) { this.counter = 0; } accesses changes['resetFlag'] without checking existence, causing runtime error when other inputs change. if (changes['resetFlag'] && changes['resetFlag'].previousValue === true) { this.counter = 0; } checks previous true, wrong condition.
  4. Final Answer:

    if (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; } -> Option D
  5. Quick Check:

    Check currentValue true on input change [OK]
Quick Trick: Check currentValue === true in changes to reset [OK]
Common Mistakes:
  • Ignoring previousValue and currentValue difference
  • Resetting counter on wrong condition
  • Not checking if changes object has resetFlag

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes