Bird
0
0

Given the component code below, what will be logged when the items array is updated by adding a new item?

medium📝 component behavior Q13 of 15
Angular - Performance Optimization
Given the component code below, what will be logged when the items array is updated by adding a new item?
items = [{id: 1, name: 'A'}, {id: 2, name: 'B'}];

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

Template:
<div *ngFor="let item of items; trackBy: trackByFn">{{item.name}}</div>
ARendering throws an error due to trackBy function
BAll items are re-rendered and logged
CNo items are rendered
DOnly the new item is rendered and logged
Step-by-Step Solution
Solution:
  1. Step 1: Understand how trackBy works with unique IDs

    The trackByFn returns the unique id of each item, so Angular can track items by their IDs.
  2. Step 2: Effect of adding a new item

    When a new item is added, Angular uses trackByFn to detect only the new item and renders just that one, not the entire list.
  3. Final Answer:

    Only the new item is rendered and logged -> Option D
  4. Quick Check:

    trackBy with unique ID renders only changed items [OK]
Quick Trick: trackBy returns unique id to render only changed items [OK]
Common Mistakes:
  • Assuming all items re-render on update
  • Thinking trackBy causes errors if function returns id
  • Believing no items render after update

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes