【问题标题】:Angular - pass pipe as variableAngular - 将管道作为变量传递
【发布时间】:2019-04-11 10:25:13
【问题描述】:

如何存储和使用来自变量的管道信息?

我已经搜索了很多,但找不到解决方案。

我想要实现的是将任何有效的管道信息作为变量(十进制、百分比、日期、自定义等)传递。下面举个简单的例子:

parent.component.ts:

columnsDef = {
  value: 0.35,
  pipeInfo: 'percent:"0.2-2":"pt-BR"'
};

parent.component html:

<app-display-component [columnsDef]="columnsDef"></app-display-component>

app-display.component html:

<h1> {{ columnsDef.value | columnsDef.pipeInfo }}</h1>

预期的输出是百分比格式的值,但我得到的只是一个模板解析错误:

ERROR 错误:未捕获(在承诺中):错误:模板解析错误:解析器错误:意外令牌'。'

【问题讨论】:

    标签: angular angular-pipe


    【解决方案1】:

    您可以创建一个自定义管道,该管道将另一个管道作为参数并将其应用于给定的值。

    这是一个由@balu 在this answer 创建的动态管道示例。有关详细信息,请参阅链接。

    import {
        Injector,
        Pipe,
        PipeTransform
    } from '@angular/core';
    
    
    @Pipe({
      name: 'dynamicPipe'
    })
    export class DynamicPipe implements PipeTransform {
    
        public constructor(private injector: Injector) {
        }
    
        transform(value: any, pipeToken: any, pipeArgs: any[]): any {
            if (!pipeToken) {
                return value;
            }
            else {
                let pipe = this.injector.get(pipeToken);
                return pipe.transform(value, ...pipeArgs);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 2022-07-29
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2020-12-05
      相关资源
      最近更新 更多