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!
The trackBy used to improve the performance of the angular project. It is usually not needed only when your application running into performance issues. The angular ngFor directive may perform poorly with large applications.
So angular does not know whether it is old objects collection or not and that's why it destroys old list and then recreates them. This can cause a problem when we are dealing with a large number of objects or list and performance issues will arise. So to avoid this we can use trackBy with ngFor directive.
The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item. Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the items that changed. That's all.
Angular came up with the trackBy directive, which is optionally passed into ngFor to help identify unique items in our arrays. TrackBy and ngFor together allow Angular to detect the specific node element that needs to change or be added instead of rebuilding the whole array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With