Angular 6

What Is trackBy in Angular? | When to Use in ngFor and ng-repeat?

The “track by” expression to specify unique keys.  The “track by” takes a function that has two arguments: index and item. If “track by” is given, Angular tracks changes by the return value of the function.

Understanding About *ngFor Mechanisms:-
By default, when you use *ngFor without “track by”, *ngFor tracks array of objects changing through object identity.

If you are going to modify (add, update, remove) any element of *ngFor, then update the tracking algorithm by providing your object id to the “track by”function.”

Why use “track by”with ngFor directive?
The “ngFor” directive may perform poorly with large lists.

A small change to the list like, adding a new item or removing an existing item may trigger several DOM manipulations.

Syntax of ngFor Angular:
<tr *ngFor="let user of users; let i = index">
    <td>{{user.name}}</td>
    <td>{{i}}</td>
</tr>

Example of *ngFor with trackBy in Angular:
<div *ngFor="let user of users; trackBy: user.id">
    {{user.id}} - {{user.name}}
 </div> 


As an example - AngularJs track by,
<div ng-repeat="user in user.userList track by user.UserId">
    {{user.name}}
</div>

Here UserId is unique id and the name of user can be same. So use “track by user.UserId” for ignores error.

Note - Angular does not allow duplicates in ng-repeat directive. So I got an error - ngRepeat:dupes.


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^