Use of Track By in AngularJs

What is the use of track by in angular js ?

Angular js uses key to associate the DOM element with the items in the model or collection that you are using in ng-repeat.You cannot use duplicate key in angular js while using ng-repeat. To avoid this problem, you can use "track by" with ng-repeat.

In track by you have to use angular expression that will be used to uniquely identify the each items in collection or model. "track by" tells the angular js that how angular js will track the association between DOM and the model (i.e. collection). Internally angular js uses "track by $id(obj)" for this purpose. You can use track by $index if you do not have a unique identifier.

If you are using "track by" then it will avoid generating DOM elements every times for element that are already rendered. It improves the rendering performance.

Run the below example:

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <title>Track By</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>  
  7. </head>  
  8.   
  9. <body ng-app="">  
  10.     <div ng-repeat="item in [12,15,15,11]"> {{item}} </div>  
  11.     <div ng-repeat="item in [12,15,15,11] track by $id(obj)"> {{item}} </div>  
  12.     <div ng-repeat="item in [12,15,15,11] track by $index"> {{item}} </div>  
  13. </body>  
  14.   
  15. </html>  

Note:

  1. ng-repeat in First and second div will throw following error (you can check in your browser console),

    "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in [12,15,15,11] track by $id(obj), Duplicate key: undefined:undefined, Duplicate value: 15"

    It is because of duplicate item in array [12,15,15,11].

  2. Angular Js internally use $id(obj) for track by.

  3. ng-repeat in third div will not throw error and work properly because we have used "track by $index". It will solve the problem of duplicate key.

For more details visit http://know4grow.blogspot.in/2016/04/track-by-in-angular-js.html

Hope you have enjoyed. Thanks for reading.