我已经编写了一个文本输入指令,以支持 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, ''));
}
关于javascript - 支持十进制数的 Number 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55932377/