该手册明确声明它接受一个数字表达式,没有别的:
数字表达式 | 货币[:currencyCode[:symbolDisplay[:digitInfo]]]
管道非常简单,可以扩展和使用,而不是CurrencyPipe
符合预期的行为:
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
@Pipe({name: 'currency'})
export class LooseCurrencyPipe extends CurrencyPipe {
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
return super.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
要创建具有不同名称的新管道,CurrencyPipe
可以将其注入自定义管道:
@Pipe({name: 'looseCurrency'})
export class LooseCurrencyPipe implements PipeTransform {
constructor(private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
为了CurrencyPipe
通过 DI 注入,它应该额外添加到模块提供程序中:
declarations: [LooseCurrencyPipe, ...],
providers: [CurrencyPipe, ...],