【发布时间】:2019-12-21 02:55:59
【问题描述】:
我想使用 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
}
}
但是一路上我发现需要在组件类中创建一个函数。
我尝试了这些,但似乎不起作用:
*ngFor="let item of collection; trackBy:index"
*ngFor="let item of collection; let i = index; trackBy:i"
没有自定义函数有没有办法通过索引进行跟踪?
感谢您的任何回答!
【问题讨论】:
-
之所以叫管道,是因为你用的是管道。在此处查看此文档 - angular.io/guide/pipes
标签: angular