Angular 5 - currencyPipe

时间:2018-02-07 17:02:12

标签: angular pipe currency currency-pipe

我对Angular中已经内置的CurrencyPipe有疑问。

我需要使用CurrencyPipe显示货币符号,但除非我提供输入数字,否则我无法使用它。

因为CurrencyPipe使用当前的区域设置来获取货币符号,所以我认为输入的数字可以是可选的。

当前行为:

{{ 1 | currency:'USD' }} --> $1

需要的行为:

{{ null | currency:'USD' }} --> $

你们是否知道默认管道是否可以这样做? 谢谢!

7 个答案:

答案 0 :(得分:8)

试试这个简单的自定义货币管道

{{ null | CustomeCurrency }}</p>

import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({ name: 'CustomeCurrency' })
export class CustomCurrencyPipe implements PipeTransform {

constructor(private currencyPipe: CurrencyPipe) { }

transform(value: any, currency: string, symbol: boolean = false): string {
     if (value != null)
        return this.currencyPipe.transform(value, currency, symbol);
    return this.currencyPipe.transform(0, currency, symbol).split('0.00')[0];
 }
}

答案 1 :(得分:4)

Angular v5中的货币管道已更改。 symbolDisplay选项(第三个参数)现在是一个字符串而不是一个布尔值。接受的值是&#34;代码&#34;,&#34;符号&#34;或&#34;符号缩小&#34;。

答案 2 :(得分:4)

如果收到错误消息在Angular v5中货币管道已更改。现在,symbolDisplay选项(第三个参数)是一个字符串,而不是布尔值。可接受的值为“ code”,“ symbol”或“ symbol-narrow”。然后请参阅Angular文档以寻求帮助,使用此页上的代码示例来解决此问题:https://angular.io/api/common/CurrencyPipe

答案 3 :(得分:1)

您可以用货币符号替换DEFAULT_CURRENCY_CODE并添加一个空格。

app.module.ts>提供程序

providers: [ { provide: DEFAULT_CURRENCY_CODE, useValue: 'LKR ' } ],

答案 4 :(得分:0)

我用自定义管道(以符号作为参数)解决了问题,因为我需要控制何时以及如何显示符号。

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

@Injectable()
@Pipe({ name: '$' })
export class MoneyPipe implements PipeTransform {
  transform(value: number, symbol: string = null, decimalDelimiter: string = ",", thousandsDelimiter: string | null = "." ): any {
    if(!value) return symbol ? symbol + " -" : "";

    let roundValue = value.toFixed(Math.max(0, ~~2));
    let valueToReturn = roundValue.replace('.', decimalDelimiter);

    if(thousandsDelimiter) valueToReturn = this.setThousandsSign(valueToReturn, thousandsDelimiter);
    return symbol ? symbol + " " + valueToReturn : valueToReturn;
  }

  private setThousandsSign(value: string, delimiter: string): string {
    return value.split("").reverse().map((str, index) => {
      if(index <= 3) return str;

      return (index%3)===0 ? str+delimiter : str;
    }).reverse().join("");
  }
}

那是HTML。

{{order.price | $}}

使用自定义符号。

{{order.price | $:'€'}}

答案 5 :(得分:0)

   {{ money | currency:'USD':'symbol' }}

答案 6 :(得分:0)

尝试

${{amount | number: '2.2'}}

如果amount=5,则输出-> $5.00

如果amount=null,则输出-> $