【问题标题】:ngFor trackBy function with custom parameters具有自定义参数的 ngFor trackBy 函数
【发布时间】:2018-03-15 01:55:50
【问题描述】:

trackBy 函数(例如在 ngFor 中)提供两个参数:索引和项目(来自被迭代的集合)。有没有办法将附加信息(作为参数?)传递给 trackBy 函数?

我的情况是,我可能会为我的组件的每个实例(包含 ngFor)迭代各种类型,并使用不同的标识字段名称。理想情况下,我希望能够传递第三个参数,指示应该读取我的项目中的哪个字段。

【问题讨论】:

    标签: angular ngfor angularjs-track-by


    【解决方案1】:

    我知道这个问题已经有一年多了,但我想添加另一个选项:

    您可以创建一个 Angular 管道,将附加参数作为参数并返回 TrackByFunction。这种管道的使用如下所示:

    <div *ngFor="let item of items; trackBy: (myParameter | myTrackByFn)">
    

    管道的代码如下:

    @Pipe({ name: 'myTrackByFn' })
    export class MyTrackByFnPipe implements PipeTransform {
    
      transform<T>(myParameter: any): TrackByFunction<T> {
        return (index: number: item: T) => {
          // ...
        };
      }
    }
    

    这种方法带来的好处之一是您可以跨组件重用管道,无需在每个组件中重新实现 trackBy 函数。

    您可以在Ben Nadel's post 中阅读有关此方法的更多信息。

    【讨论】:

      【解决方案2】:

      bind 方法可以帮你做到这一点

      template.html

      <div *ngFor="let item of items; trackBy: trackByFn.bind(this, 'name')">
        {{ item }}
      </div>
      

      component.ts

      items = [
        {
          id: 1,
          name: 'name1'
        },
        {
          id: 2,
          name: 'name2'
        }
      ]
      trackByFn(customParam, index, item) {
        return item[customParam];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-25
        • 2017-12-19
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多