我使用这样的管道号并且工作正常
{{ item.price | number }}
我想在输入元素文本中使用此管道
<input type="text" name="price" [ngModel]="price | number" (ngModelChange)="price=$event" >
在输入法中输入数字时,我想用逗号分隔3个数字
从输入文本中的222222222
到222,222,222
当我输入数字以显示此错误时:
错误错误:InvalidPipeArgument:管道的'2,22222不是数字' 'DecimalPipe'
如何解决此问题? stackblitz
答案 0 :(得分:3)
您需要为此创建自定义管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberPipe'
})
export class NumberPipePipe implements PipeTransform {
transform(val) {
val = this.format_number(val, '');
return val;
}
format_number(number, prefix) {
let thousand_separator = ',',
decimal_separator = '.',
regex = new RegExp('[^' + decimal_separator + '\\d]', 'g'),
number_string = number.replace(regex, '').toString(),
split = number_string.split(decimal_separator),
rest = split[0].length % 3,
result = split[0].substr(0, rest),
thousands = split[0].substr(rest).match(/\d{3}/g);
if (thousands) {
let separator = rest ? thousand_separator : '';
result += separator + thousands.join(thousand_separator);
}
result = split[1] != undefined ? result + decimal_separator + split[1] : result;
return prefix == undefined ? result : (result ? prefix + result : '');
};
}