【问题标题】:Angular2 - ngFor trackby index without custom functionAngular2 - ngFor trackby index没有自定义功能
【发布时间】: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


【解决方案1】:

你做不到。以前是可能的,但由于存在很多错误,他们停止了对它的支持。现在你需要传递函数。

feature request,可以关注。

【讨论】:

  • 非常感谢!我已经关注了这个问题!
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2019-03-20
  • 1970-01-01
  • 2020-12-07
  • 2020-10-25
  • 2017-06-25
相关资源
最近更新 更多