How to Use TrackBy in Angular 8 application

In this article, we are going to learn how to use Track By in Angular applications.

In every application, to run the application faster we need to check the performance of our application. A ngular provides a method called trackBy which is used to track our incoming data every time we request from API.

Suppose we have some data coming from API request into the collection and we need to change the data over the web page using ngFor directive. In this case Angular will remove all the DOM elements that are associated with the data and will create them again in the DOM tree. That means a lot of DOM manipulations will happen if a large amount of data is coming from the API.

Prerequisites

  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed

Step 1

Let’s create a new Angular project using the following NPM command,

ng new trackBy   

Step 2

Now, let’s create a new component by using the following command,

ng g c trackBy-example  

Step 3

Now, open the trackBy-example.component.html file and add the following code in the file,

<h4 style="text-align: center;">{{SampleMessage}}</h4>    
<div class="row">    
  <div class="col-12 col-md-12">    
    <div class="card">    
      <div class="card-body position-relative">    
        <div class="table-responsive cnstr-record product-tbl">    
          <table class="table table-bordered heading-hvr">    
            <thead>    
              <tr>    
                <th width="50">Art.No </th>    
                <th>Brand</th>    
                <th>Price/Unit</th>    
                <th>Provider</th>    
                <th>P. Art. N</th>    
                <th>S. A/C</th>    
              </tr>    
            </thead>    
            <tbody>    
              <tr *ngFor="let product of companyProduct;">    
                <td align="center">{{product.ArtNo}}</td>    
                <td>{{product.Brand}}</td>    
                <td>{{product.Price }}</td>    
                <td>{{product.Provider}}</td>    
                <td>{{product.ProviderArtNo}}</td>    
                <td>{{product.SalesAccount}}</td>    
              </tr>    
            </tbody>    
          </table>    
          <button (click)='getNewCompanies()'>New Companies</button>    
        </div>    
      </div>    
    </div>    
  </div>    
</div>    

Here we are not using trackBy function yet.

In the below code we can check how to apply trackby with our structural direcrtive *ngFor

<tr *ngFor="let product of companyProduct; trackBy:trackByArtNo">  

Step 4

Now, open the trackBy-example.component.ts file and add the following code in this file,

import { Component, OnInit } from '@angular/core';  
import { ProductsService } from '../product.service';  
  
@Component({  
  selector: 'app-trackby',  
  templateUrl: './trackby.component.html'  
})  
export class TrackbyComponent implements OnInit {  
  companyProduct: any[];  
  SampleMessage="Example of Angular Fetching records using TrackBy";  
  
  constructor(private productService: ProductsService) {  
  
  }  
  ngOnInit() {  
    this.companyProduct = this.productService.getAllProductsUsingTrackBy();  
  }  
  
  getNewCompanies(): void {  
    this.companyProduct = this.productService.getAllProductsUsingTrackByExample();  
  }  
  trackByArtNo(index: number, companyProduct: any): string {  
    return companyProduct.ArtNo;  
  }  
  
}  

TrackBy function will take two arguments, the  first is index and the second is current item. We can return the unique identifier as a return argument.

trackByArtNo(index: number, companyProduct: any): string {    
   return companyProduct.ArtNo;    
 }  

Step 5

Now, open the product.service.ts file and add the following code,

import { Injectable } from '@angular/core';  
  
@Injectable()  
  
export class ProductsService {  
  employees: any[]; 
  
  constructor() {  
  }  
  
  getAllProductsUsingTrackBy() {  
    return this.employees = [  
      {  
        ProductId: 1,  
        ArtNo: "100",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 7810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "101",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 2310.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "102",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 7810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "103",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 5810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      }  
    ];  
  }  
  
  getAllProductsUsingTrackByExample() {  
    return this.employees = [  
      {  
        ProductId: 1,  
        ArtNo: "100",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 7810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "101",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 2310.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "102",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 7810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "103",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 5810.23,  
        BuyAccount: "123",  
        SalesAccount: "321"  
      },  
      {  
        ProductId: 1,  
        ArtNo: "104",  
        Provider: "OppoProvider",  
        ProviderArtNo: "1Yu",  
        Brand: "Oppo",  
        Price: 4770.23,  
        BuyAccount: "143",  
        SalesAccount: "211"  
      },  
    ];  
  }  
  
}  

Now it’s time to run the project by using ‘npm start’ or ‘ng serve’ command and check the output.

As in the below image when we click on “New Companies” it will add one new entry in the table .

This is image title

If we use normal *ngFor directive without using trackBy function Angular application will remove all the DOM elements and will recreate them again in the DOM tree, even if the same data is coming. This can slow down our application performance if the data is large in number.

This is image title

But with the help of trackBy it will not create a new DOM as we can see in the below image. It just gets added only the new data in the DOM which will increase the application performance.

This is image title

Conclusion

In this article, we have seen how to use trackBy with NgFor in Angular 8 Application.

Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.

Thank you!

#angular #NgFor in Angular 8 #programming

How to Use TrackBy in Angular 8 application
13.60 GEEK