首页 > 解决方案 > Number directive to support decimal numbers

问题描述

I have written a directive for text input, to support int values.

Here is it

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, ''));
  }
}

And 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>

But I need it to support decimal values. For example 99.5

How do I need to modify it?

标签: javascriptangulartypescriptangular2-directives

解决方案


尝试这个:

@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


推荐阅读