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!