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

6

Whenever I see an article on the internet about optimizing rendering time for ng-repeat , I see comments about the track by option.

Example:

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

As far as I understand, track by does some sort of indexing in iteration.

But why exactly does it say that track by improves ng-repeat performance?

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

    
asked by anonymous 16.11.2017 / 19:07

1 answer

3

Whenever you have a 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 this identifier instead of the object instance, e.g. item in items track by item.id . If you do not want to reload your data later, it 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.

Also, even if you do not define a ngRepeat , you implicitly use a single track by for each item.

  

Default tracking: $ id (): $$hashKey is equivalent to item in items . This implies that the DOM elements will be associated by item identity in the collection.

In practical terms,% default is the same as re-creating everything from scratch if your list is updated, since there is nothing that identifies your existing content, even if identical to those already in 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:

link

    
03.03.2018 / 05:27