具有本地小数分隔符处理的十进制数的角度输入指令

问题描述 投票:0回答:1

我正在开发一个 Angular 项目,我需要为处理十进制数字的输入字段创建一个自定义指令。我面临的挑战是确保与本地小数分隔符的兼容性。

该指令应满足以下要求:

  1. 接受带或不带前导零的十进制数字,例如“0.123”或“.456”。
  2. 自动调整为用户本地小数点分隔符(, 或 .)。
  3. 负数限制。
  4. 限制非数字和非小数字符。
<input type="text" decimalNumbersOnly>
javascript angular typescript angular-directive
1个回答
0
投票

@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
    }
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.