The Problem:

When you need to iterate over a collection in Angular 2, you will probably use the ngFor directive that will instantiate a template once per item from the collection.

If we need at some point to change the data in the collection, for example as a result of an API request, we have a problem because Angular can’t keep track of items in the collection and has no knowledge of which items have been removed or added.

As a result, Angular needs to remove all the DOM elements that associated with the data and create them again. That means a lot of DOM manipulations especially in a case of a big collection, and as we know, DOM manipulations are expensive.

Note: when I’m saying “change the data” I’m referring to replace the collection with new objects and not keeping the same reference.

Let’s see this in action:

The Solution:

We can help Angular to track which items added or removed by providing a trackBy function. The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item.

Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the items that changed.

That’s all. you can play with the code here.

Things to not miss:

☞ Please tap or click “︎❤” to help to promote this piece to others.