可以使用Angular的自定义指令来实现只允许输入数字和两位小数,以逗号分隔的功能。下面是一个示例代码:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appNumberFormat]'
})
export class NumberFormatDirective {
constructor(private el: ElementRef) { }
@HostListener('input', ['$event'])
onInputChange(event: any) {
const initialValue = this.el.nativeElement.value;
let newValue = initialValue.replace(/[^0-9.,]/g, ''); // 只允许数字、逗号和句点
newValue = this.formatNumber(newValue); // 格式化数字
if (initialValue !== newValue) {
this.el.nativeElement.value = newValue;
event.stopPropagation();
}
}
private formatNumber(value: string): string {
const parts = value.split('.');
const integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 每三位数字加一个逗号
let decimalPart = '';
if (parts.length > 1) {
decimalPart = parts[1].substring(0, 2); // 只保留两位小数
}
return integerPart + (decimalPart ? '.' + decimalPart : '');
}
}
在模板中使用该指令:
这样,输入框就只能输入数字、逗号和句点,并且会自动格式化为每三位数字加一个逗号的形式,保留两位小数。