javascript - 支持十进制数的 Number 指令

标签 javascript angular typescript angular2-directives

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

关于javascript - 支持十进制数的 Number 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55932377/

相关文章:

javascript - 如何通过单击删除..?

javascript - typescript map : key and value swapped on iteration

typescript - 将自定义指令绑定(bind)到 Angular2 中的 Observable

javascript - 是否可以迭代数组中的每个项目并输出为 HTML?

Angular 警告 "Warning:Can' t 解析所有参数...”

javascript - 组件自动完成 VueJS

javascript - 我如何按最近创建的列表列出提要中的帖子?

typescript - 根据具有默认值的参数返回 Promise 或 boolean 值

javascript - d3.js 数据第一次未绑定(bind)

javascript - 使用 jQuery 遍历列表项