TrackBy helps Angular remember items in a list to update only what changes. This makes your app faster and smoother.
TrackBy in ngFor in Angular
Start learning this pattern below
Jump into concepts and practice - no test required
<div *ngFor="let item of items; trackBy: trackByFunction">{{item.name}}</div> trackByFunction(index: number, item: any): any { return item.id; }
The trackBy function receives the index and the item from the list.
It should return a unique identifier for each item, usually an ID.
id property.<div *ngFor="let user of users; trackBy: trackByUserId">{{user.name}}</div> trackByUserId(index: number, user: any): number { return user.id; }
<div *ngFor="let product of products; trackBy: trackByIndex">{{product.name}}</div> trackByIndex(index: number, product: any): number { return index; }
This component shows a list of products. Clicking the button shuffles the list order. Using trackById helps Angular keep track of each product by its id, so it only updates the order without recreating all list items.
import { Component } from '@angular/core'; @Component({ selector: 'app-trackby-demo', template: ` <h2>Product List</h2> <button (click)="shuffle()">Shuffle Products</button> <ul> <li *ngFor="let product of products; trackBy: trackById"> {{product.name}} (ID: {{product.id}}) </li> </ul> ` }) export class TrackByDemoComponent { products = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' } ]; trackById(index: number, product: any): number { return product.id; } shuffle() { this.products = this.products .map(value => ({ value, sort: Math.random() })) .sort((a, b) => a.sort - b.sort) .map(({ value }) => value); } }
Without trackBy, Angular recreates all list items on changes, which can cause flicker and lose input focus.
Always use a unique and stable identifier for best results.
TrackBy improves list rendering performance by identifying items uniquely.
Use it when lists update often or are large.
It helps Angular update only changed items, making apps faster and smoother.
Practice
trackBy in an ngFor directive in Angular?Solution
Step 1: Understand what
ngFordoesngForrepeats a template for each item in a list, rendering them in the view.Step 2: Identify the role of
trackBytrackByhelps Angular know which items changed by uniquely identifying them, so it only updates those items instead of re-rendering the whole list.Final Answer:
To improve performance by uniquely identifying list items during updates -> Option AQuick Check:
TrackBy improves performance = C [OK]
- Thinking trackBy sorts or filters items
- Believing trackBy changes item styles
- Assuming trackBy removes duplicates
trackBy in an ngFor loop?Solution
Step 1: Recall the correct
The correct syntax uses a semicolon and the keywordngForsyntax withtrackBytrackByfollowed by the function name without parentheses.Step 2: Compare options
*ngFor="let item of items; trackBy: trackByFn"matches the correct syntax:*ngFor="let item of items; trackBy: trackByFn". Others either miss the keyword or use parentheses incorrectly.Final Answer:
*ngFor="let item of items; trackBy: trackByFn" -> Option BQuick Check:
Correct syntax includes 'trackBy:' keyword [OK]
- Omitting 'trackBy:' keyword
- Adding parentheses after function name
- Using '=' instead of ':'
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>Solution
Step 1: Understand how trackBy works with unique IDs
ThetrackByFnreturns the uniqueidof each item, so Angular can track items by their IDs.Step 2: Effect of adding a new item
When a new item is added, Angular usestrackByFnto detect only the new item and renders just that one, not the entire list.Final Answer:
Only the new item is rendered and logged -> Option DQuick Check:
trackBy with unique ID renders only changed items [OK]
- Assuming all items re-render on update
- Thinking trackBy causes errors if function returns id
- Believing no items render after update
trackBy function used in an ngFor loop:trackByFn(index: number, item: any) {
return index + 1;
}Solution
Step 1: Analyze the returned value from trackByFn
The function returnsindex + 1, which changes if the list order changes or items are added/removed.Step 2: Understand why this causes problems
Returning a value based on index is not stable for tracking because indexes shift, causing Angular to think items changed incorrectly.Final Answer:
It returns a non-unique value causing incorrect tracking -> Option AQuick Check:
trackBy must return stable unique IDs, not shifting indexes [OK]
- Thinking index is always safe to return
- Ignoring that indexes shift on list changes
- Assuming missing return type causes syntax error
trackBy. Which trackBy function below correctly handles this scenario to avoid unnecessary re-renders when the list updates?Solution
Step 1: Identify the unique property for tracking
Users may have duplicate names, so usinguser.nameis not reliable. The uniqueuser.idis the best choice.Step 2: Evaluate each option
A usesuser.name(not unique), B usesuser.id(stable and unique), C usesindex(unstable), D returns the wholeuserobject (not recommended).Final Answer:
trackByFn(index: number, user: any) { return user.id; } -> Option CQuick Check:
Use unique IDs for trackBy to avoid re-renders [OK]
- Using non-unique properties like names
- Using index which changes on list updates
- Returning the whole object causing errors
