Bird
0
0

Consider the following Angular component snippet:

medium📝 component behavior Q4 of 15
Angular - Performance Optimization
Consider the following Angular component snippet:
items = [
  { id: 10, name: 'X' },
  { id: 20, name: 'Y' },
  { id: 30, name: 'Z' }
];

trackById(index: number, item: any) { return item.id; }

// Update
items[1] = { id: 20, name: 'Y Updated' };

What will Angular do when this update occurs with the trackById function in place?
AAll items will be re-rendered because the array reference changed.
BOnly the second item will be re-rendered because its id matches and content changed.
CNo items will be re-rendered because the id did not change.
DAngular will throw an error due to object mutation.
Step-by-Step Solution
Solution:
  1. Step 1: Understand trackBy behavior

    Angular uses the trackBy function to identify items by their unique id.
  2. Step 2: Effect of updating an item

    Replacing the second item with a new object with the same id causes Angular to detect a change only for that item.
  3. Step 3: Rendering outcome

    Angular will re-render only the updated item, not the entire list.
  4. Final Answer:

    Only the second item will be re-rendered because its id matches and content changed. -> Option B
  5. Quick Check:

    trackBy id matches, so only changed item updates [OK]
Quick Trick: trackBy identifies items by id, updating only changed ones [OK]
Common Mistakes:
  • Assuming entire list re-renders on object mutation
  • Believing Angular throws error on object replacement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes