0
0
Angularframework~3 mins

Why TrackBy in ngFor in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny function can make your Angular lists lightning fast and smooth!

The Scenario

Imagine you have a long list of items displayed on a webpage, and every time the list updates, Angular redraws the entire list from scratch.

This causes flickering and slow performance, especially on slower devices.

The Problem

Without trackBy, Angular treats every item as new and recreates all DOM elements, even if only one item changed.

This wastes time and resources, making the app feel sluggish and unresponsive.

The Solution

The trackBy function tells Angular how to identify items uniquely, so it only updates the changed items.

This keeps the rest of the list intact, improving speed and user experience.

Before vs After
Before
*ngFor="let item of items"
After
*ngFor="let item of items; trackBy: trackById"
What It Enables

It enables smooth, fast updates of large lists by reusing existing elements instead of rebuilding everything.

Real Life Example

Think of a chat app where new messages appear without the entire message list blinking or resetting scroll position.

Key Takeaways

Without trackBy, Angular recreates all list items on any change.

trackBy helps Angular identify items uniquely for efficient updates.

This improves performance and user experience in dynamic lists.