Angular2 - ngFor trackby index without custom function

Viewed 5564

I want to use ngFor trackBy index. And I find some way like below

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
    </ul>
    <button (click)="getItems()">Refresh items</button>
  `,
})
export class App {

  constructor() {
    this.collection = [{id: 1}, {id: 2}, {id: 3}];
  }

  getItems() {
    this.collection = this.getItemsFromServer();
  }

  getItemsFromServer() {
    return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
  }

  trackByFn(index, item) {
    return index; // or item.id
  }
}

But all the way I found need to create a function in component class.

I try these but seem to not work:

*ngFor="let item of collection; trackBy:index"

*ngFor="let item of collection; let i = index; trackBy:i"

Is there any way to track by index without custom function?

Thanks for any answer!

1 Answers

You can't do it. It was possible before but due to a lot of bugs they discontinued its support. Now you need to pass function.

There is feature request so you can follow it.

Related