Thursday, 16 February 2017

Improving Angular 2 Performance while using ngFor

When you iterate over an array or collection most probably you use ngFor directive to bind the data of collection into your DOM elements.

Problem !

Here the big problem is, If at some point of time you wish to change the data in the collection, for example maybe as a result of an API request, Then the Angular can’t keep track of items in the collection and has no knowledge of which items have been removed or added as a results it creates the DOM again. That means this has a lot of DOM manipulations.

Solution ..

Here comes the solution, ngFor directive has a property called track by.

So what do these do? They help Angular to associate key with the DOM elements and tracks which items are added or removed.

Angular’s ngFor defaults tracks object identity for you, which is fast, but it can be more faster if we use track by unique object ID in ngFor. Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.

   <li *ngFor="let student of students; trackBy: student.id;">
    ...
   </li>

Optionally, we can use track by index but that is not advisable as the index may be subject to change if you reorder your collection. Using a unique identifier allows Angular to locate that DOM node associated with the object much faster

No comments:

Post a Comment