X Tutup
Skip to content

[ngFor] trackBy behaviour #6907

@cexbrayat

Description

@cexbrayat

Something surprised me as I was giving a try to the new trackBy feature.

In the following example, an array of users is generated every second with two users (always the same names) and a random score for each one.
The ngFor is used to display the list of user with their score.
trackBy can be useful here to track the user by their name rather than by their reference (which changes every second).

But if we do this in Angular 2 beta.3, the score is never updated.
Is it on purpose? AFAIK, in AngularJS 1.x, that was not the case (the score would be updated even if the ngRepeat was using a trackBy).

@Component({
  template: `<div *ngFor="#user of users trackBy userByName">{{user.name}} -> {{user.score}}</div>`
})
class TestCmp {
  users: any;
  constructor() {
    window.setInterval(() => this.users = [
      {name: 'user1', score: Math.random()},
      {name: 'user2', score: Math.random()}], 
   1000);
  }

  userByName(index, user) {
    return user.name;
  }
}

cc @kara @mhevery

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    X Tutup