How to use trackBy() Function with ngFor Directive in Angular ?
Last Updated :
24 Apr, 2025
In this article, we will see How to use the 'trackBy' function with 'ngFor' Directive in Angular, along with understanding their basic implementation through illustrations.
The NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page. The trackBy Function facilitates finding the unique items in the list & accordingly updating the DOM while manipulating the data in the list. Implementing the NgFor Directive with the trackBy function can enhance the display of the lists by providing a custom tracking technique.
Steps for Installing & Configuring the Angular Application
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Project Structure
It will look like the following:

Approach 1
In this approach, on each ngDoCheck triggered for the ngForOf directive, angular checks what objects have changed. It uses differs for this process and each uses the trackBy function to compare the current object with the new one.
Example: In this example, we have created an identifier called id. This identifier will be returned to the trackBy function in the HTML.
HTML
<!-- app.component.html -->
<div style="width: 70%;">
<h2 style="color: green">
GeeksforGeeks
</h2>
<h2>
How to use 'trackBy' with 'ngFor' in Angular ?
</h2>
<ul>
<li *ngFor="let item of items; trackBy: trackByFn">
{{ item.id }} - {{ item.name }}
</li>
</ul>
</div>
JavaScript
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: "./app.component.html",
})
export class AppComponent {
items = [
{ id: 1, name: 'React' },
{ id: 2, name: 'Angular' },
{ id: 3, name: 'Typescript' },
{ id: 4, name: 'Java' }
];
trackByFn(index: number, item: any): number {
return item.id;
}
}
JavaScript
// app.module.ts
import { NgModule }
from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { HttpClientModule }
from '@angular/common/http';
import { CardModule }
from "primeng/card";
import { ButtonModule }
from 'primeng/button';
import { AppComponent }
from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CardModule,
HttpClientModule,
ButtonModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }