在 Angular 2 中,我如何使用反射(或我在这里称之为的任何名称)来使用管道?我有一个带有管道名称的字符串(如“小写”),我想仅使用该字符串调用管道。

例如:

JSON

var cols = [{ dataProperty: "city", pipeName: "lowercase"},{ dataProperty: "state", pipeName: "uppercase"}]
var rows = [{city: 'Walla Walla', state: 'wa'}];

HTML(Angular 组件摘录)
{{ rowData[col.dataProperty] | this.[col.pipeName] }}

但是这段代码不起作用。

我用什么代替 this.[col.pipeName] 来给我动态调用 uppercaselowercase (或我在 pipeName 中定义的任何管道,假设它是我的代码可以访问的管道)的等效项?

最佳答案

如果您的 json 数据将被硬编码

var cols = [{dataProperty: "city",  pipe: new LowerCasePipe()},
            {dataProperty: "state", pipe: new UpperCasePipe()}]

然后在你的模板html中
{{col.pipe.transform(rowData[col.dataProperty])}}

所有默认的 angular 管道都实现了 PipeTransform 接口(interface),它上面有 变换 方法。

如果您的数据来自 api

您可以将其保留为 pipeName: "uppercase"并从字典中拉出相应的管道。
export class PipeManager {
  private static _pipes = {
    'upperCase': new UpperCasePipe(),
    'lowerCase': new LowerCasePipe(),
    'currency': new CurrencyPipe('en')
  };

  public static PipeForKey(key: string) {
    return PipeManager._pipes[key];
  }
}

然后在你的模板html中
{{PipeManager.PipeForKey(col.pipeName).transform(rowData[col.dataProperty])}}

这个解决方案可以稍微清理一下,但希望你能明白。

关于Angular 如何从带有管道名称的字符串中调用管道?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49181908/

10-17 02:54