javascript - 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?
解决方案
尝试这个:
@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, ''));
}
推荐阅读
- r - 拆分块数据并在 R 中获得最大/最小值
- scala - 强制案例对象的名称
- html - @media 屏幕不工作,怎么了?
- django - 静态 url 在常规页面 url 之后
- r - R中的反向分组条形图
- objective-c - NSRegularExpression enumerateMatchesInString 正确用法
- amazon-web-services - 如何使用aws服务对我的url执行get操作以获取数据
- json - 如何处理对话流中自定义有效负载的答案?
- javascript - React-native:按日期对数据进行分组并像议程项目一样显示
- nginx - Nginx 代理到 CFSS 连接被拒绝