How To Use trackBy With ngFor In Angular 8

Introduction

 
In this article, we will learn how to improve our application performance using trackBy.
 
Example
 
If we want to display data in the collections for the first time, it will go through DOM manipulation after updating the records. Then the updated records remove all the DOM elements associated with the data and create them again. This problem creates Dom manipulations, which are expensive in our application.
 
TrackBy
 
TrackBy is used to track the latest value in the dom without refreshing the full dom element. It only updates the new data.
 
Prerequisites
  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed
Create an Angular project
 
Step 1
 
Create a new Angular project using the following NPM command:
  1. ng new trackByExample  
Step 2
 
Now, let's create a new component using the following command:
  1. ng g c trackBy   
Step 3
 
Now open the trackby.component.html file and add the following code:
  1. <div class="card">    
  2.   <div class="card-body pb-0">    
  3.     <h1 style="text-align: center;">Example with trackBy</h1>    
  4.     <div class="row">    
  5.       <div class="col-12 col-md-12">    
  6.         <div class="card">    
  7.     
  8.           <div class="card-body position-relative">    
  9.             <div class="table-responsive cnstr-record product-tbl">    
  10.               <table class="table table-bordered heading-hvr">    
  11.                 <thead>    
  12.                   <tr>    
  13.                     <th width="50">Art.No    
  14.                     </th>    
  15.                     <th>Brand</th>    
  16.                     <th>Provider</th>    
  17.                     <th>P. Art. N</th>    
  18.                     <th>S. A/C</th>    
  19.                     <th>Price </th>    
  20.                   </tr>    
  21.                 </thead>    
  22.     
  23.                 <tbody *ngFor="let product of products; let i = index;trackBy:trackByProductId">    
  24.                   <tr>    
  25.                     <td align="center">{{product.ArtNo}}</td>    
  26.                     <td>{{product.Brand}}</td>    
  27.                     <td>{{product.Provider}}</td>    
  28.                     <td>{{product.ProviderArtNo}}</td>    
  29.                     <td>{{product.SalesAccount}}</td>    
  30.                     <td>{{product.Price}}</td>    
  31.                   </tr>    
  32.                 </tbody>    
  33.               </table>    
  34.               <button class="btn btn-primary" (click)="addNewProd()">Add new Product</button>    
  35.             </div>    
  36.           </div>    
  37.         </div>    
  38.       </div>    
  39.     </div>    
  40.   </div>    
  41. </div>     
Step 4
 
The next step is to open the trackBy.component.ts file and add the following code:
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-trackby-example',  
  5.   templateUrl: './trackby-example.component.html',  
  6.   styleUrls: ['./trackby-example.component.css']  
  7. })  
  8. export class TrackbyExampleComponent implements OnInit {  
  9.   products = [];  
  10.   country: any;  
  11.   priceToDisplay = [];  
  12.   
  13.   constructor() {  
  14.   }  
  15.   ngOnInit() {  
  16.     this.products = [{  
  17.       'ArtNo': 1,  
  18.       'Brand''Apple',  
  19.       'Provider''Mr.Anil',  
  20.       'ProviderArtNo''Pr123',  
  21.       'SalesAccount''Sa456',  
  22.       'Price': 123000  
  23.     },  
  24.     {  
  25.       'ArtNo': 2,  
  26.       'Brand''One Plus',  
  27.       'Provider''Mrs.Kiran',  
  28.       'ProviderArtNo''Pr234',  
  29.       'SalesAccount''Sa345',  
  30.       'Price': 52300  
  31.     }, {  
  32.       'ArtNo': 3,  
  33.       'Brand''Samsung',  
  34.       'Provider''Mr.Ramesh',  
  35.       'ProviderArtNo''Pr345',  
  36.       'SalesAccount''Sa234',  
  37.       'Price': 23000  
  38.     }, {  
  39.       'ArtNo': 4,  
  40.       'Brand''Mi',  
  41.       'Provider''Mr.Suresh',  
  42.       'ProviderArtNo''Pr456',  
  43.       'SalesAccount''Sa123',  
  44.       'Price': 12300  
  45.     }];  
  46.   }  
  47.   
  48.   addNewProd() {  
  49.     this.products = [{  
  50.       'ArtNo': 1,  
  51.       'Brand''Apple',  
  52.       'Provider''Mr.Anil',  
  53.       'ProviderArtNo''Pr123',  
  54.       'SalesAccount''Sa456',  
  55.       'Price': 123000  
  56.     },  
  57.     {  
  58.       'ArtNo': 2,  
  59.       'Brand''One Plus',  
  60.       'Provider''Mrs.Kiran',  
  61.       'ProviderArtNo''Pr234',  
  62.       'SalesAccount''Sa345',  
  63.       'Price': 52300  
  64.     }, {  
  65.       'ArtNo': 3,  
  66.       'Brand''Samsung',  
  67.       'Provider''Mr.Ramesh',  
  68.       'ProviderArtNo''Pr345',  
  69.       'SalesAccount''Sa234',  
  70.       'Price': 23000  
  71.     }, {  
  72.       'ArtNo': 4,  
  73.       'Brand''Mi',  
  74.       'Provider''Mr.Suresh',  
  75.       'ProviderArtNo''Pr456',  
  76.       'SalesAccount''Sa123',  
  77.       'Price': 12300  
  78.     }, {  
  79.       'ArtNo': 5,  
  80.       'Brand''Redmi',  
  81.       'Provider''Ms.Swara',  
  82.       'ProviderArtNo''Pr567',  
  83.       'SalesAccount''Sa121',  
  84.       'Price': 13000  
  85.     }];  
  86.   }  
  87.   trackByProductId(index: number, product: any) {  
  88.     return product.ArtNo;  
  89.   }  
  90. }  
Output
 
In the above image, we can see that after we click on the Add New Product button, it will remove all the elements from the DOM and recreates it again, as we can see on the right-hand side of the above image.
 
In the above image, we can see that after clicking on Add new Product button, only the updated record is added to the DOM as we used trackBy in the structural directive to track the updated record. If we click on the button again, then it will not reflect the change as it's already updated. This only improves our application performance.
 

Conclusion

 
In this article, we learned how to use trackBy with *ngFor, which helps to improve performance.
 
I hope you have enjoyed this article as much as I have enjoyed writing and coding the examples.
 
Please let me know how to improve it.


Similar Articles