支持十进制数的 Number 指令

Number directive to support decimal numbers

我已经编写了一个文本输入指令,以支持 int 值。

就在这里

import { NgControl } from '@angular/forms';
import { HostListener, Directive } from '@angular/core';

@Directive({
  exportAs: 'number-directive',
  selector: 'number-directive, [number-directive]'
})
export class NumberDirective {
  private el: NgControl;
  constructor(ngControl: NgControl) {
    this.el = ngControl;
  }
  // Listen for the input event to also handle copy and paste.
  @HostListener('input', ['$event.target.value'])
  onInput(value: string) {
    // Use NgControl patchValue to prevent the issue on validation
    this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
  }
}

和HTML

 <div class="form-group">
                    <label>{{ l("RoomWidth") }}</label>
                    <input
                        decimal-number-directive
                        #roomWidthInput="ngModel"
                        class="form-control nospinner-input"
                        type="text"
                        name="roomWidth"
                        [(ngModel)]="room.roomWidth"
                        maxlength="32"
                    />
                </div>

但我需要它支持十进制值。例如 99.5

需要怎么修改?

试试这个:

@HostListener('input', ['$event.target.value'])
onInput(value: string) {
  // Use NgControl patchValue to prevent the issue on validation
  this.el.control.patchValue(value.replace(/[^0-9].[^0-9]/g, ''));
}

Working_Demo

在我的情况下,我也需要考虑两个连续点并替换字符。也许可以用正则表达式写,但这对我有用。 例如,如果您键入或粘贴 45.456.6,它将被替换为 45.4566

 @HostListener('input', ['$event']) onInputChange(event) {
    let initalValue: string = this.el.nativeElement.value;
    initalValue = initalValue.replace(/[^\.|0-9]/g, '');
    // elimina le seconde occorrenze del punto
    const count = (initalValue.match(/\./g) || []).length;
    for (let i = 1; i < count; i++) {
      initalValue = this.repaceSecondDotOccurrence(initalValue);
    }
    this.el.nativeElement.value = initalValue;
  }


  repaceSecondDotOccurrence(inputString): string {
    let t = 0;
    return inputString.replace(/\./g, function (match) {
      t++;
      return (t === 2) ? '' : match;
    });
  }