【问题标题】:How to pass function as arg Pipe angular2如何将函数作为 arg Pipe angular2 传递
【发布时间】:2017-05-27 07:08:36
【问题描述】:

我想要一个通用字段过滤器,它将过滤器函数作为参数并在filter中使用它

import {Injectable, Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'FieldsFilter'
})
@Injectable()
export class FieldsFilter implements PipeTransform {
  transform(fields: any[], args: any[]): any {
    return fields.filter(args[0]);//pass function to filter
  }
}

所以我可以在多个地方使用不同的过滤器功能。

如何通过过滤功能?

【问题讨论】:

    标签: angular angular2-pipe


    【解决方案1】:
    @Pipe({
      name: 'FieldsFilter'
    })
    @Injectable()
    export class FieldsFilter implements PipeTransform {
      transform(fields: any[], f): any {
        return fields.filter((e) => f(e));
      }
    }
    

    很久以前改变了,额外的管道参数被传递给单个参数,而不是作为数组形式的单个参数。

    【讨论】:

    • 尝试在参数函数中引用 this 时出现错误。怎么绑定?
    • 我明白了。将函数分配给组件中的一个字段,例如this.f = this.filterFuntion.bind(this);,然后将f 传递给管道。
    • .bind(this) 的优势恕我直言,方法支持多少参数并不重要,=> 你需要(a, b, c) => myFunc(a, b, c)。不过,对于内联函数,我更喜欢 =>
    • @GünterZöchbauer 谢谢!但是我如何将它用作 ngFor 的过滤器,意思是说它应该将它绑定到一个 prop 并且每次它更改时都应该调用它?
    • @JoeB 最好用一些代码来创建一个新问题来演示您尝试完成的工作。我不明白你的评论有什么问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2016-04-29
    • 2017-02-25
    • 2019-10-08
    相关资源
    最近更新 更多