Open In App

How to use trackBy() Function with ngFor Directive in Angular ?

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

z132

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 { }


Output:

Recording-2023-10-27-at-022258

Approach 2

In this approach, we are using the trackBy function with *ngFor in Angular to specify a track-by function directly within the template using an arrow function. This can be especially useful when you don’t need a separate method for tracking.

Example: In the given example, we define the trackBy function as an arrow function directly within the template. The function returns the book.ISBN as the unique identifier for tracking.

Javascript




// app.component.ts
  
import { Component } from '@angular/core';
  
@Component({
    selector: 'app-root',
    template: `
        <h2 style="color: green">GeeksforGeeks</h2>
        <h2>How to use 'trackBy' with 'ngFor' in Angular ?</h2>
        <ul>
            <li *ngFor=
            "let book of books; trackBy: trackByISBN">
                {{ book.title }}
            </li>
        </ul>`,
})
export class AppComponent {
    books = [
        { ISBN: '978-0451526533'
          title: 'To Kill a Mockingbird' },
        { ISBN: '978-1982137274'
          title: '1984' },
        { ISBN: '978-0141439587'
          title: 'Pride and Prejudice' },
        { ISBN: '978-0743273565'
          title: 'The Great Gatsby' },
    ];
  
    trackByISBN(index: number, book: any): string {
        return book.ISBN;
    }
}


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 { }


Output:

Recording-2023-10-27-at-024419



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads