我已经编写了用于输入文本的指令,以支持int值。
这是
"posts" : [
{
"_id" : ObjectId("5cc8478118195b71e2ccd517"),
"post" : "hey users",
"createdTime" : ISODate("2019-04-30T13:02:57.621Z")
},
{
"_id" : ObjectId("5cc853ec0a5fde0e431898f3"),
"post" : "hey friends it's my final post",
"createdTime" : ISODate("2019-04-30T13:55:56.119Z")
}
],
和HTML
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, ''));
}
}
但是我需要它支持十进制值。例如99.5
我该如何修改?
答案 0 :(得分: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, ''));
}
答案 1 :(得分:0)
就我而言,我还需要考虑两个构成要点并替换角色。也许可以用正则表达式写,但这对我有用。 例如,如果您键入或粘贴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;
});
}