我想使用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)
没有自定义功能,有什么方法可以按索引进行跟踪吗?
感谢您的回答!
| 归档时间: |
|
| 查看次数: |
3488 次 |
| 最近记录: |