Number指令支持十进制数

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

我已经为文本输入编写了一个指令,以支持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

我该如何修改它?

javascript angular typescript angular2-directives
1个回答
3
投票

试试这个:

@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


0
投票

在我的情况下,我也需要考虑两个连续点,并取代caracter。也许可以用正则表达式写,但这对我有用。例如,如果您键入或粘贴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;
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.