Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - ngFor trackby index without custom function

Tags:

angular

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!

like image 246
someblue Avatar asked Sep 20 '17 03:09

someblue


People also ask

What is the difference between trackBy and ngFor?

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.

Why must you use the ngFor directive in conjunction with the trackBy function?

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.

How does ngFor trackBy work?

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.

Why trackBy is used in angular?

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.


1 Answers

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.

like image 143
alexKhymenko Avatar answered Oct 31 '22 03:10

alexKhymenko