我注意到Angular 2中有一个名为CurrencyPipe的管道,它会从一个数字中过滤掉一些小数.这也增加了ISO货币指标,即"美元"或任何其他本地货币.
我的问题是输出显示如下:
USD123
Run Code Online (Sandbox Code Playgroud)
没有美元和123之间的空间,这真的是首选行为吗?我是否必须为此编写自己的管道,或者我可以做些什么来添加空间?
这是一些代码:
<span>{{ product.price | currency:'USD' }}</span>
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为CurrencyPipe依赖Intl.NumberFormat并且没有选择.
这就是说,你可以切换显示$,而不是USD与symbolDisplay设定参数true:
<span>{{ product.price | currency:'USD':true }}</span>
Run Code Online (Sandbox Code Playgroud)
这将显示:$123哪个更好;-)如果这不适合您,您需要实现自定义管道格式化您的号码...
有关详细信息,请参阅以下链接
您可以使用第一个字母的伪元素使用一些聪明的CSS来解决这个问题,在您的span中添加一个类:
<span class="price">{{ product.price | currency:'USD':true }}</span>
Run Code Online (Sandbox Code Playgroud)
并在你的CSS中添加:
.price {
display: inline-block;
}
.price::first-letter {
padding-right: 0.3em;
}
Run Code Online (Sandbox Code Playgroud)
第一个规则确保您在块容器框中的价格(::first-letter对inline显示块有效),第二个规则在货币符号后添加一些额外的填充.
你可以根据自己的喜好调整一下......
你真的需要使用货币管吗?您始终可以将货币与金额分开:
<span class="price">{{ product.currency }} {{ product.price|number:'1.2-2'}}</span>
或者在你的情况下:
<span class="price">USD {{ product.price|number:'1.2-2'}}</span>
您可以按如下方式覆盖管道。确保将其包含在模块中
import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
@Pipe({name: 'currency'})
export class MyCurrencyPipe extends CurrencyPipe implements PipeTransform {
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
const currencyFormat = super.transform(value, currencyCode, symbolDisplay, digits);
const firstDigit = currencyFormat.search(/\d/);
return currencyFormat.substring(0, firstDigit) + ' ' + currencyFormat.substr(firstDigit);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
制作自己的自定义货币管道。
import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({ name: 'myCurrency' })
export class MyCurrencyPipe implements PipeTransform {
transform(num: any, currencyCode: string, showSymbol: boolean, digits: string): any {
let value = new CurrencyPipe(navigator.language).transform(num, currencyCode, showSymbol, digits);
let firstDigit = value.match(/\d/);
let symbol = value.slice(0, firstDigit.index);
let amount = value.slice(firstDigit.index);
return symbol + " " + amount;
}
}
Run Code Online (Sandbox Code Playgroud)
并在HTML中使用它, 例如
{{amount | myCurrency: currencyCode :true:'1.0-2'}}
Run Code Online (Sandbox Code Playgroud)
DISPLAY参数从 更改boolean为string
显示字符串 | 布尔值
货币指标的格式。以下之一:
- code:显示代码(例如 USD)。
- 符号(默认):显示符号(例如$)。
- symbol-narrow:对于具有两个货币符号的区域设置,使用窄符号。例如,加元 CAD 的符号为 CA$ 和窄符号 $。如果区域设置没有窄符号,则使用区域设置的标准符号。
- 字符串:使用给定的字符串值而不是代码或符号。例如,空字符串将抑制货币和符号。
布尔值(在 v5 中标记为已弃用):对于符号为 true,对于代码为 false。
选修的。默认为“符号”。
文档: https: //angular.io/api/common/CurrencyPipe
您可以使用字符串格式覆盖货币和符号。
字符串:使用给定的字符串值而不是代码或符号。例如,空字符串将抑制货币和符号。
<span>{{ product.price | currency:'USD ' }}</span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13611 次 |
| 最近记录: |