Angular Trackby to improve ngFor Performance

Angular Trackby option improves the Performance of the ngFor if the collection has a large no of items and keeps changing. Learn why we need it and how to use it to improve the performance of the ngFor.

Trackby in ngFor

We usengFor to display a iterable items like array in a list or tabular format. For Example the following code iterates over the movies collection and displays each movie inside an ul

The Angular creates a li element for each movie. So if there are n number of movies, the angular inserts the n number of li nodes into the DOM

But the data will not remain constant. The user will add a new movie, delete a movie, sort the list in a different order, or simply refresh the movie from the back end. This will force the angular to render the template again.

The easiest way to achieve that is to remove the entire list and render the DOM again. But this is inefficient and if the list is large it is a very expensive process.

To avoid that the Angular uses the object identity to track the elements in the collection to the DOM nodes. Hence when you add an item or remove an item, the Angular will track it and update only the modified items in the DOM.

But if you refresh the entire list from the back end, it will replace the objects in the movie collection with the new objects. Even if the movies are the same, Angular will not be able to detect as the object references have changed. Hence it considers them new and renders them again after destroying the old ones.

The following example shows what happens when we refresh the entire list. The App displays the list of movies. it has option to add a movie, remove a movie and refresh the entire movie.

Angular Track by renders the view on refresh

You can see from the above example, that Angular renders the entire DOM every time we click on refresh.

Trackby

We can solve this problem by providing a function to the trackBy option that returns a unique id for each item. The ngFor will use the unique id returned by the trackBy function to track the items. Hence even if we refresh the data from the back end, the unique id will remain the same and the list will not be rendered again.

The trackBy takes a function that has two arguments: index and the current item. It must return a id that uniquely identifies the item. The following example returns the title as the unique id.

In the template assign the newly created trackByFn to trackBy option in the ngFor statement.

Trackby multiple fields

You can also trackby multiple fields as shown below

Reference

  1. Change Propagation in ngFor

3 thoughts on “Angular Trackby to improve ngFor Performance”

  1. Oh, I need to use it in my app… Use a lot of ngFor there and the events are triggered at the every simple mouse move

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top