In Focus

TrackBy With ngFor Directive In Angular Application

In this post, we are going to see a very interesting thing, trackyBy with ngFor directive.

Why use trackyBy with ngFor directive

  • ngFor directive may perform poorly with large lists.
  • A small change to the list, like adding a new item or removing an existing item, may trigger several DOM manipulations.

Let’s look at an example. Suppose, we are having an “Employee Component” in the project.

Now, consider this below code in the employee.component.ts file.

Note
  1. The constructor() initializes the “employees” property with 4 employee objects.
  2. getEmployees() method returns another list of 5 employee objects (The 4 existing employees + a new employee object).

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-employee',  
  5.   templateUrl: './employee.component.html',  
  6.   styleUrls: ['./employee.component.css']  
  7. })  
  8. export class EmployeeComponent implements OnInit {  
  9.   employees: any[];  
  10.   ngOnInit(){}  
  11.   constructor() {  
  12.       this.employees = [  
  13.           {  
  14.               code: '1001', name: 'drashti', gender: 'Female',  
  15.               salary: 55500  
  16.           },  
  17.           {  
  18.               code: '1002', name: 'namrata', gender: 'Female',  
  19.               salary: 57000  
  20.           },  
  21.           {  
  22.               code: '1003', name: 'shreeja', gender: 'Female',  
  23.               salary: 59000  
  24.           },  
  25.           {  
  26.               code: '1004', name: 'shreenil', gender: 'Male',  
  27.               salary: 65000  
  28.           }  
  29.       ];  
  30.   }  
  31.   
  32.   getEmployees(): void {  
  33.       this.employees = [  
  34.         {  
  35.           code: '1001', name: 'drashti', gender: 'Female',  
  36.           salary: 55500  
  37.       },  
  38.       {  
  39.           code: '1002', name: 'namrata', gender: 'Female',  
  40.           salary: 57000  
  41.       },  
  42.       {  
  43.           code: '1003', name: 'shreeja', gender: 'Female',  
  44.           salary: 59000  
  45.       },  
  46.       {  
  47.           code: '1004', name: 'shreenil', gender: 'Male',  
  48.           salary: 65000  
  49.       },  
  50.           {  
  51.               code: '1005', name: 'tejas', gender: 'Male',  
  52.               salary: 67000  
  53.           }  
  54.       ];  
  55.   }  
  56. }  

Now, look at this code in employeeList.component.html.

  1. <div class="container">  
  2.     <table class="table">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Code</th>  
  6.                 <th>Name</th>  
  7.                 <th>Gender</th>  
  8.                 <th>Annual Salary</th>  
  9.   
  10.             </tr>  
  11.         </thead>  
  12.         <tbody>  
  13.             <!--  -->  
  14.             <tr *ngFor='let employee of employees'>  
  15.                 <td>{{employee.code}}</td>  
  16.                 <td>{{employee.name}}</td>  
  17.                 <td>{{employee.gender}}</td>  
  18.                 <td>{{employee.salary}}</td>  
  19.   
  20.             </tr>  
  21.             <tr *ngIf="!employees || employees.length==0">  
  22.                 <td colspan="5">  
  23.                     No employees to display  
  24.                 </td>  
  25.             </tr>  
  26.         </tbody>  
  27.     </table>  
  28.     <br />  
  29.     <button class="btn btn-primary" (click)='getEmployees()'>Refresh Employees</button>  
  30. </div>  

Ok now, let’s check what we are exactly doing. At the moment, we are not using trackBy with ngFor directive. So what the above code will do is that:

  1. When the page initially loads, we see 4 employees.
  2. When we click the "Refresh Employees" button, we see the fifth employee also.
  3. It will look like it has just added the additional row for the fifth employee. But that's not true, it effectively destroyed all the <tr> and <td> elements of all the employees and recreated them.
  4. To confirm this, launch your browser with developer tools by pressing F12.
  5. Then, click on the "Elements" tab and expand the <table> and then <tbody> elements.
  6. At this point, again, click the "Refresh Employees" button and you will notice all the <tr>elements are briefly highlighted. This indicates that they are destroyed and recreated.

Here is the initial page load screen with 4 employee objects.

TrackBy With ngFor Directive In Angular Application 

When we click on the “Refresh Employees” button.

TrackBy With ngFor Directive In Angular Application 

In the above screen, you can check that when the button is clicked, it will add a fifth object of Employee but along with that, it will destroy the previously added objects and recreate them. You can see in your browser that they all are highlighted.

This happened because, by default, Angular keeps track of these Employee objects using their object references and when we click the button, we are returning new object references (by calling getEmployees() method). So, Angular does not know whether it is old objects collection or not and that’s why it destroys the old list and recreates a new one.

 This can cause a problem when we are dealing with a large number of objects or list. The performance issues will arise. So, to avoid this, we can use trackBy with ngFor directive.

Now, we will add a trackBy function in the employee.component.ts file.

The trackBy function takes the index and the current item as arguments and returns the unique identifier by which that item should be tracked. In our case, we are tracking by Employee code.

  1. trackByEmpCode(index: number, employee: any): string {  
  2.     return employee.code;  
  3. }  

And also, make the following changes in employeeList.component.html.

Notice that along with ngFor, we also specified trackBy.

  1. <tr *ngFor='let employee of employees; trackBy:trackByEmpCode'

Now, run the application.

TrackBy With ngFor Directive In Angular Application 

At this point, run the application and check the developer tools. When you click "Refresh Employees" the first time, only the row of the fifth employee is highlighted indicating only that <tr> element is added. When you click further, nothing is highlighted. It means that none of the <tr> elements are destroyed or added as the Employees collection has not changed. Even now, we get different object references when we click the "Refresh Employees" button, but as Angular is now tracking employee objects using the employee code instead of object references, the respective DOM elements are not affected.