What is the importance of using "track by" in "ng-repeat"?

Asked

Viewed 3,874 times

6

Whenever I see any article on the internet on how to optimize the render time of ng-repeat, I see comments on the option track by.

Example:

<div ng-repeat="task in tasks track by task.id"></div>

From what I understand, the track by makes a kind of index identification in the iteration.

But why exactly is it said that track by improves the performance of ng-repeat?

Is there any negative impact of using ng-repeat with track by instead of just using the ng-repeat "pure"?

1 answer

3


Whenever you have one track by that identifies the line, when updating your data, you do not need to recreate the entire DOM, those that are already properly identified and exist in the update will simply be ignored.

Best Practice: If you are Working with Objects that have a Unique Identifier Property, you should track by this Identifier Instead of the Object instance, e.g. item in items track by item.id. Should you Reload your data later, ngRepeat will not have to rebuild the DOM Elements for items it has already rendered, Even if the Javascript Objects in the Collection have been substituted for new ones. For large Collections, this significantly improves Rendering performance.

Still, even if you don’t define one track by, implicitly is used a $$hashKey single for each item.

Default tracking: $id(): item in items is equivalent to item in items track by $id(item). This implies that the DOM Elements will be Associated by item Identity in the Collection.

Practically speaking, track by default is the same as recreating everything from scratch if your list is updated, since there is nothing that identifies its inserted content as existing, even if identical to those already on the list, and with a unique property this rework does not exist, since only what is not actually on your list will be inserted.

Sources:

https://docs.angularjs.org/api/ng/directive/ngRepeat

Browser other questions tagged

You are not signed in. Login or sign up in order to post.