Bird
0
0

What is the best way to ensure Angular detects the change?

hard🚀 Application Q15 of 15
Angular - Change Detection
You have a list of user objects and want to display their names in Angular. You update the list by replacing it with a new array but the UI does not refresh. What is the best way to ensure Angular detects the change?
ARestart the Angular application.
BModify the existing array without replacing it.
CUse <code>setTimeout</code> to delay the update.
DManually call <code>changeDetectorRef.detectChanges()</code> after updating the list.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Angular's change detection on object references

    Angular detects changes when object references change or manual detection runs.
  2. Step 2: Analyze options for updating the list

    Replacing the array changes reference but sometimes Angular needs manual detectChanges() call to update UI immediately.
  3. Step 3: Evaluate other options

    Modifying existing array may not trigger detection; setTimeout delays but is unreliable; restarting app is extreme.
  4. Final Answer:

    Manually call changeDetectorRef.detectChanges() after updating the list. -> Option D
  5. Quick Check:

    Manual detectChanges() ensures UI updates [OK]
Quick Trick: Call detectChanges() after replacing data arrays [OK]
Common Mistakes:
MISTAKES
  • Modifying array without changing reference
  • Using setTimeout as a fix
  • Restarting app instead of fixing detection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes