Bird
0
0

How should you fix this to ensure the child updates efficiently?

hard🚀 Application Q15 of 15
Angular - Change Detection
You have a parent component passing a list of items to a child component with OnPush strategy. The parent updates the list by adding a new item using items.push(newItem). The child does not update. How should you fix this to ensure the child updates efficiently?
AUse <code>items = [...items, newItem]</code> to create a new array reference
BCall <code>markForCheck()</code> on the child's ChangeDetectorRef after push
CChange child's strategy to Default
DManually trigger <code>detectChanges()</code> in the child after push
Step-by-Step Solution
Solution:
  1. Step 1: Understand OnPush and input references

    OnPush detects changes only when input references change, so mutating the array with push keeps the same reference.
  2. Step 2: Apply immutable update

    Using items = [...items, newItem] creates a new array reference, triggering OnPush change detection in the child.
  3. Final Answer:

    Use items = [...items, newItem] to create a new array reference -> Option A
  4. Quick Check:

    Immutable input updates trigger OnPush = B [OK]
Quick Trick: Create new input arrays to trigger OnPush updates [OK]
Common Mistakes:
MISTAKES
  • Mutating arrays with push expecting updates
  • Relying on manual detectChanges() calls
  • Changing strategy unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes