← Back to list

Magic of trackBy in *ngFor

trackBy is a function of *ngFor which

Sunil Majhi · 2023-11-15 19:26 · 0 claps · 0.4 min read paywalled
#angular #typescript #trackby #javascript #angular-concepts
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Magic of trackBy in *ngFor

*trackBy is a function of ngFor which**

  1. uniquely identifies list elements.
  2. updates only DOM items affected by change

By using trackBy we can

  1. Optimizes UI changes(appending to list, reordering items, …)
  2. Preserve UI state(cursor position, focus,…)
  3. useful for animating newly added items

trackBy function must:

  1. be pure
  2. have unique output(list items should be uniquely identified)
  3. be fast(Don’t do many things in the function)

Code:

<div *ngFor = "let item of items; trackBy: trackByItemId">
  <list-item [item] = "item"></list-item>
</div>

trackByItemId(_:number, item: Item): string {
  return item.id
}

Improvised Code:

// track-by-item-id.helper.ts

export function trackByItemId(_:number, item: Item): string {
  return item.id
}

export class MyFancyComponent{
  trackByItemId = trackByItemId;
}

메타데이터
post_id
307eecbaeb43
slug
magic-of-trackby-in-ngfor-307eecbaeb43
url
https://medium.com/@msunil037/magic-of-trackby-in-ngfor-307eecbaeb43
canonical_url
https://medium.com/@msunil037/magic-of-trackby-in-ngfor-307eecbaeb43
author_url
https://medium.com/@msunil037
status
ok
fetched_at
2026-06-21 15:33:18