Step 2: NgFor Fixed with TrackBy

The Solution

By using trackBy, Angular can track which items changed and only update those specific elements. Notice in the console that existing components are not recreated when adding new cards.

Note: we also removed the *ngFor directive and replaced it with @for.

Fixed Code:


<@for (card of cards; track card.id) {
  <app-card-item [card]="card" appLifecycleLogger></app-card-item>
}
          
Card 1

Card 1

Component Instance ID: 38a24a

Card 2

Card 2

Component Instance ID: snur9b

Card 3

Card 3

Component Instance ID: c0kblb