javascript - Angular 2 - trackBy function, what does it really do? -
i under impression trackby function used when trying optimize performance of *ngfor, if changes, dom doesn't have rebuild.
however, recently, came across situation when trackby fixed wrong behavior.
take example: https://plnkr.co/edit/nrgdwoikampsbmwaomoj?p=preview focus on hobbies section, html:
<div> <h2>hobbies</h2> <div *ngfor="let h of user.hobbies; trackby:customtrackby; let = index"> #{{i}} - {{h | json}}<br /> <input [(ngmodel)]="h.name" name="hobby_name_{{i}}" /> <br /><br /> <select [(ngmodel)]="h.type_id" name="type_{{i}}"> <option *ngfor="let t of types" [value]="t.id">{{t.type}}</option> </select> <br /> <br /> <button class="btn btn-warn" (click)="remove(i)">remove</button> <br /><br /> </div> </div> i had explicitly define part: trackby:customtrackby in first *ngfor. if trackby removed, , following steps performed:
- remove first item
- add new item
in case, inputs of first item replaced content of second item (both fields have same content), however, values in model correct.
trackby solves issue, why?
i appreciate kind of explanation. if not right place ask kind of questions please redirect me correct one. thanks.
update
here's example of wrong behavior: https://plnkr.co/edit/u8yajkfhcpivqy0wcjt7?p=preview remove first item (cycling) , add new item (add button) , see how both values same default value (bf replaced "default value" though model stays correct).
*ngfor default tracks items object identity.
if have primitive values array of strings, , use them in
<div *ngfor="let item of items; let i=index"> <input [(ngmodel)]="item" name="item{{i}}"> </div> and edit 1 item, *ngfor gets in trouble, because identity of edited item has changed.
with ngfortrackby can tell *ngfor track item index, above code work fine when edit fields.
another use case when want *ngfor track items custom object id property instead of object identity.
Comments
Post a Comment