Improving *ngFor Performance Through trackBy In Angular

Introduction

We bind data to the HTML using *ngFor directive in Angular. We have an array of iterable items which is passed as an input to the directive. *ngFor is a structural directive in Angular. It iterates over the collection of data. Using ngFor we can display changes in the data display at runtime. The data will be updated by default in the display iterated by ngFor. Whenever there is a collection of day to display in Angular, we will generally use ngFor to show in the DOM.

Striping first, last, even and odd of the list

Sometimes we want to apply some class on the first element of the list, or even element of the list. This can be achieved using the syntax mentioned below. first,  last, even, odd are assigned to some variable.
index: this is the current loop iterator
first: a boolean value which conveys whether the item is the first item in the iteration.
last: a boolean value which conveys whether the item is the last one in the iteration.
even: a value indicating whether this item has an even index.
odd: a boolean value indicating whether this item has an odd index.

How *ngFor works?

*ngFor works when we add or remove the elements from the list. It will continuously be adding or removing elements from the DOM. If the list gets modified, ngFor will work constantly to work on this operation. This is a costly operation. Suppose if we have changes only a single element in the array, then also all the elements are redrawn in the DOM which is an expensive task. *ngFor directive can't detect if the elements in the new array are already present in the DOM. It treats it as a new reference completely and tries to redraw it from scratch. 

Using trackBy to improve performance

We can improve the performance of the *ngFor directive using trackBy function in Angular. The trackBy function takes two arguments: the index and the element. Now when we do any modification in the array then the Angular can detect the change using the unique identifier. Therefore only the changes items will be added or removed instead of the whole collection in the DOM. We will use trackBy when:

  • When we have a large collection to iterate over.
  • Our logic needs modification in the array items. 
  • When performance is our concern. 
We can use trackBy to track the list-items. We can help Angular to track the items using the trackBy function. The trackBy function takes the index and the current item as a parameter and returns the unique identifier for this item.  

<div>
      <ul>
            <li *ngFor="let e of employee; trackBy: trackByFn">
              {{e.id}}{{e.name}}
            </li>
     </ul>
</div>

 trackByFn(index, item) {

return index; //or item.id

}

Comments