问题描述
如何存储和使用变量中的管道信息?
How may I store and use pipe information from variables?
我已经搜索了很多,但是找不到解决方案.
I've already searched a lot but couldn't find a solution for that.
我要实现的目标是将任何有效的管道信息作为变量传递(十进制,百分比,日期,自定义等).遵循一个简单的示例:
What I'm trying to achieve is passing any valid pipe information as a variable (decimal, percent, date, custom, etc). Follows a simple example:
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>
期望的输出是格式化为百分比的值,但是我得到的只是一个模板解析错误:
The expected output is the value formatted as a percentage, but all I get is a template parse error:
错误错误:未捕获(承诺):错误:模板解析错误:分析器错误:意外的令牌'.'
ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Unexpected token '.'
推荐答案
您可以创建一个自定义管道,该管道将另一个管道作为参数,并将其应用于指定的值.
You can create a custom pipe which gets another pipe as an argument and apply it to the value given to it.
这是@balu在此答案中创建的动态管道的示例.有关更多信息,请参见链接.
Here is an example of a dynamic pipe created by @balu in this answer. See the link for more info.
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);
}
}
}
这篇关于角度-传递管道为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!