我正在开发一个 Angular 项目,我需要为处理十进制数字的输入字段创建一个自定义指令。我面临的挑战是确保与本地小数分隔符的兼容性。
该指令应满足以下要求:
<input type="text" decimalNumbersOnly>
@Directive({
selector: 'input[decimalNumbersOnly]',
})
export class NumberDirectiveDecimal {
private whatDecimalSeparator() {
const n: number = 1.1;
const locale = window.navigator.language;
const sel: string = n.toLocaleString(locale).substring(1, 2);
return sel;
}
decimalSeparator: string = '';
constructor(private _el: ElementRef) {
this.decimalSeparator = this.whatDecimalSeparator();
}
@HostListener('input', ['$event']) onInputChange(event: any) {
const initialValue = this._el.nativeElement.value;
const regexPattern = new RegExp(`[^0-9\\${this.decimalSeparator}]`, 'g');
this._el.nativeElement.value = initialValue.replace(regexPattern, '');
const dotCount = (
this._el.nativeElement.value.match(
new RegExp(`\\${this.decimalSeparator}`, 'g')
) || []
).length;
if (dotCount > 1) {
this._el.nativeElement.value = this._el.nativeElement.value.slice(0, -1); // Remove the last dot if there are multiple dots
}
if (initialValue !== this._el.nativeElement.value) {
event.stopPropagation(); // Stop the event propagation if the input value is changed
}
}
}