Angular ngFor trackBy

Kesavi Kanesalingam
3 min readFeb 23, 2020

--

NgFor is a structural directive, meaning that it changes the structure of the DOM . It’s point is to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding.

Let’s understand it with example. Let’s modify the FruitList.Component.ts file as shown below.The constructor() of the FruitList Component initialize with 5 fruits objects, on the other hand, the getFruits() method of the FruitList Component returns another collection of 8 fruit objects.

We can see in this example the (most common) syntax for using ngFor:

  • we are passing to ngFor an iteration expression
  • a loop variable named fruit is defined using the keyword let, which is consistent with Javascript syntax
  • the expression is under the form of var i of items, which is consistent with the Javascript of iteration functionality

Now let’s modify the html code as below.

In the above html code, we don’t use trackBy. When the page loads, we will see the initilalized 5 fruits. When we click on the “Refresh Fruits” button, then we will see the 6th-8th fruits as well. We will think when pressing button, only 6th-8th fruits are loading. Let’s see what happen in real.

Initilaly:

5 fruits refreshed

Click on “Refresh Fruits” button:

8 fruits refreshed

This is because Angular by default keeps track of the objects using the object references. So, when we click on the “Refresh Fruits” button we get different object references and as a result, Angular has no choice but to delete all the old DOM elements and insert the new DOM elements.

To overcome the above problem, the Angular comes with a solution that is trackBy. The trackBy function in Angular takes the current item as an argument and then it returns a unique identifier using which we can track that item. In our example, we are going to track by index of fruit.

Now we modify the code as shown below. In FruitList.Component.ts file we add this method.

In html, we change *ngFor line as below.

Now, When we click on the “Refresh Fruits” button, only 6th-8th fruits are loading.

Using trackBy doesn’t affect much if the app is small but in case it’s more complex and handles multiple transactions on view then rendering may cost on memory resources making view to fluctuate or respond slow.

So it’s a good practice to optimize application and Help Angular by adding a trackBy keyword.

--

--

No responses yet