我为了我的目的实现了这个。
例如:- 12345.67 => 12,345.67
首先,我使用 ng g pipe pipes/thousandSeparator 生成了一个 PIpe,然后我像这样编辑了该文件
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'thousandSeparator'
})
export class ThousandSeparatorPipe implements PipeTransform {
transform(nStr: any): any {
if (nStr === '') { return ''; }
let x, x1, x2, rgx;
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x[1];
rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + (x2 ? `.${x2}` : '');
}
}
我也将它添加到 app.module.ts 中的提供程序中
providers: [ThousandSeparatorPipe]
那么,我可以这样使用它。
在组件中
import { Component, OnInit } from '@angular/core';
import { ThousandSeparatorPipe } from 'src/app/pipes/thousand-separator.pipe';
@Component({
selector: 'app-my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
value = 12345.67;
constructor(private thousandSeparator: ThousandSeparatorPipe) { }
ngOnInit() {
console.log(this.thousandSeparator.transform(this.value));
}
}
在html中
<p>{{value | thousandSeparator}}</p>