【问题标题】:Angular 2 - How to use build-in pipe inside custom pipe [duplicate]Angular 2 - 如何在自定义管道中使用内置管道[重复]
【发布时间】:2017-02-15 18:44:54
【问题描述】:

我想使用内置货币管道制作自定义货币管道。我想使用的方式是{{ anyNumber | customCurrency }}. 然后在我的customCurrency 管道中,我想使用内置的货币管道。我可以根据一些逻辑决定货币管道的参数,并且不想在任何地方指定语言环境和其他参数,例如{{anyNumber | currency:'USD':false:'1:0-0'}}

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

@Pipe({
  name: 'customCurrency'
})
export class CustomCurrencyPipe implements PipeTransform {

  transform(value: any, args?: any): any {
      const defaultLocale = 'USD';
      const showSymbol = false;

      ......some logic here......      

      //HOW TO USE CURRENCY PIPE HERE?

 }

}

【问题讨论】:

  • 要么使用依赖注入,要么因为货币管道是无状态的,所以只需new 一个向上(您可以将@Inject(LOCALE_ID) 作为其构造函数参数传递)。

标签: angular angular-pipe angular2-custom-pipes


【解决方案1】:

您应该将内置管道注入到您的自定义管道中,而不是使用默认值调用它的转换方法

@Pipe({
  name: 'customCurrency'
})
export class CustomCurrencyPipe implements PipeTransform {

  constructor(public currencyPipe: CurrencyPipe) {
  }

  transform(value: any, args?: any): any {
      const currencyCode = 'USD';
      const showSymbol = false;
      return currencyPipe.transform(value, currencyCode, showSymbol);
 }

}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 2017-10-11
  • 2023-04-03
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2017-12-07
相关资源
最近更新 更多