如何在Angular 4中为数字管道指定/覆盖默认(区域设置)千位分隔符,例如?
{{p.total | number}}
?
从Angular 5开始,一个locale参数已被添加到十进制管道中,您可以在官方文档中看到:https://angular.io/api/common/DecimalPipe。这意味着您可以在调用管道时直接选择语言环境,例如:
{{p.total | number:'':'fr-FR'}}
请注意,这也将更改小数分隔符。
或者如果你想改变千位分隔符......
根据Angular关于DecimalPipe:https://v2.angular.io/docs/ts/latest/api/common/index/DecimalPipe-pipe.html的文档,没有明确的参数可以添加到管道调用中以异常地更改用于格式化的字符。
如果您不想更改整个项目的区域设置或关联的默认值,我认为您最好的方法是编写自己的管道来处理您的特殊情况。不用担心,管道非常容易编写。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberfr'
})
export class FrenchDecimalPipe implements PipeTransform {
transform(val: number): string {
// Format the output to display any way you want here.
// For instance:
if (val !== undefined && val !== null) {
return val.toLocaleString(/*arguments you need*/);
} else {
return '';
}
}
}
不要忘记将其添加到NgModule中以使用它。
数量:1234567
使用以下管道:
{{element.total | 2号'}}
为了生产1,234,567.00
并使用以下管道:
{{element.total | 2号。'}}
为了摆脱额外的0并产生1,234,567
----------------------------------------------------------------------------------------
注意'2'表示小数后的整数。
例如,当使用此管道在表中加载值0时,显示的值将为“00”(因为“2”)
要解决这个问题,请使用'1.'而是当输入值为0时。
以下是我的解决方案,它将对某人有所帮助。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'amountConverter'
})
export class AmountConverterPipe implements PipeTransform {
transform(value: number | string, locale?: string): string {
return new Intl.NumberFormat(locale, {
minimumFractionDigits: 2
}).format(Number(value));
}
}
通过更改minimumFractionDigits的值可以更改位数。在html中你可以使用如下
<span class="strong">{{Price | amountConverter:locale}}</span>
数字格式将根据区域设置的值更改。
有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat。
您可以使用与使用Angular 6.0.2测试的此示例中的区域设置:
card-component.ts
import { registerLocaleData } from '@angular/common';
import es from '@angular/common/locales/es';
import { Component, OnInit } from '@angular/core';
@Component( {
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: [ './card.component.css' ]
} )
export class CardComponent implements OnInit {
value = 1234567.987;
constructor() { }
ngOnInit() {
registerLocaleData( es );
}
}
card-component.html
<!-- result: 1.234.567,987 -->
<span>{{ value | number:'':'es' }}</span>
您可以在https://angular.io/api/common/DecimalPipe和https://angular.io/guide/i18n#setting-up-the-locale-of-your-app官方文档中查看其他可能性。
在模板中使用带区域设置的数字管道:
{{myDigit | number:'':'en'}}
如果你想配置,第一个''
是十进制的。
我知道这可能会迟到但希望它有所帮助。角度2以上
import { DecimalPipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
@Component( {
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: [ './card.component.css' ]
} )
export class CardComponent implements OnInit {
value = 1234567.987;
constructor(private decimalPipe: DecimalPipe) { }
ngOnInit() {
//here is how to get it
let newValue = this.decPipe.transform(this.value, '.2');
//you can now use the newValue
}
}
如果你想在html中这样做,那就做:
{{ value | number: '.2'}}