Angular2-没有自定义功能的ngFor跟踪索引

som*_*lue 5 angular

我想使用ngFor trackBy索引。我发现如下所示的方式

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我发现的所有方式都需要在组件类中创建一个函数。

我尝试了这些,但似乎不起作用:

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

*ngFor="let item of collection; let i = index; trackBy:i"
Run Code Online (Sandbox Code Playgroud)

没有自定义功能,有什么方法可以按索引进行跟踪吗?

感谢您的回答!

ale*_*nko 6

你不能这样做。以前是可能的,但由于存在很多错误,他们停止了支持。现在你需要传递函数。

功能请求,因此您可以遵循它。