How to use track by with ng-repeat?

Loading

In AngularJS, ng-repeat is used to loop over a list and display items dynamically. However, by default, AngularJS tracks items by their index, which can lead to performance issues, especially when updating large lists.

The track by clause helps optimize performance by uniquely identifying items based on a specific property, preventing unnecessary DOM re-renders.


1. Why Use track by in ng-repeat?

Problem Without track by

  • When modifying a list (adding, removing, or updating items), AngularJS re-renders the entire list, even if only one item changes.
  • This causes unnecessary DOM updates, slowing down performance.

Solution With track by

  • track by helps AngularJS uniquely identify each item using an ID or unique key.
  • Instead of re-rendering the whole list, AngularJS only updates the modified items.

2. Syntax of track by

<li ng-repeat="item in items track by item.id">
{{item.name}}
</li>

🔹 Here, item.id is the unique identifier for each item.
🔹 If items are added/removed, only the affected items update, not the whole list.


3. Example Without track by (Performance Issue)

JavaScript:

app.controller("ListController", function($scope) {
$scope.items = [
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Cherry" }
];

$scope.updateList = function() {
// Updating the list with the same values
$scope.items = [
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Cherry" },
{ id: 4, name: "Date" } // New item added
];
};
});

HTML Without track by

<ul>
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
<button ng-click="updateList()">Update List</button>

Issue: When clicking “Update List”, AngularJS re-renders all elements, even if they are the same.


4. Example With track by (Optimized)

HTML With track by

<ul>
<li ng-repeat="item in items track by item.id">{{item.name}}</li>
</ul>
<button ng-click="updateList()">Update List</button>

Now, when updating the list, AngularJS only adds the new item instead of re-rendering all elements.


5. Using track by $index (If No Unique ID)

If your list has no unique identifier, use $index instead:

<li ng-repeat="item in items track by $index">{{item}}</li>

Limitation: If the order of items changes, AngularJS might not recognize them properly.


6. track by with Objects and Filters

Works with filtered lists:

<li ng-repeat="item in items | filter:search track by item.id">
{{item.name}}
</li>

Works with nested objects:

<li ng-repeat="item in users track by item.profile.id">
{{item.profile.name}}
</li>

7. Key Benefits of track by

Prevents unnecessary DOM re-renders
Improves performance for large lists
Efficiently updates only modified items

When to Use track by?

✔ Large lists (100+ items)
✔ Lists with dynamic updates
✔ Lists with frequent reordering

Leave a Reply

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