我为自己创建了这个指令解决方案,它可以:
- 在焦点上将输入初始化为 0.00。
- 兼容模板驱动和 ReactiveForm。
- 删除/撤消任何非数字条目。
- 防止空输入。
- 粘贴 123ab4d5,输出:12345。
- 每千除以一个 ,
- 退格/删除兼容。
- 让我们在中间输入/删除。
- 仅正整数。



推荐:使用 [maxLength] 将用户限制到一定长度。
<input [maxLength]="9" appPriceUsd>
这是指令:
// Format USD by Reza Taba
import { DecimalPipe } from '@angular/common';
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appPriceUsd]'
})
export class PriceUsdDirective {
constructor(private elRef: ElementRef, private decimalPipe: DecimalPipe) { }
@HostListener('focus') initializeValue(): void {
if (this.elRef.nativeElement.value === '') {
this.elRef.nativeElement.value = '0.00';
}
}
@HostListener('keyup') formatUsd(): void {
let value: string;
value = this.elRef.nativeElement.value as string;
value = this.removeNonDigtis(value); // remove all non-digit values
value = this.addDecimalPoint(value); // Add . to the -2 index
value = this.applyDecimalPipe(value); // to divide every thousand
this.elRef.nativeElement.value = value;
}
removeNonDigtis(value: string): string {
let inputArray: string[] = [];
const digitArray: string[] = [];
// 12a34b to ["1", "2", "a", "3", "4", "b"]
inputArray = value.split('');
// remove any non-digit value
for (const iterator of inputArray) {
if (/[0-9]/.test(iterator)) {
digitArray.push(iterator);
}
}
return digitArray.join('');
}
addDecimalPoint(value: string): string {
const inputArray = value.split(''); // ['0', '.', '0', '0']
inputArray.splice(-2, 0, '.'); // place decimal in -2
return inputArray.join('');
}
applyDecimalPipe(value: string): string {
console.log(value);
return value === '' || value === '.'
? '0.00'
: this.decimalPipe.transform(value, '1.2-2');
}
}
希望能帮助到你。享受编码。