[有一个角度指令,应该只允许input
中的数字。其代码如下:
import {
Directive,
ElementRef,
HostListener,
ChangeDetectorRef,
Renderer2
} from "@angular/core";
@Directive({
selector: "input[onlyNumbers]"
})
export class OnlyNumbersDirective {
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
@HostListener("input", ["$event"]) onInputChange(event) {
const initValue = this.elementRef.nativeElement.value;
this.elementRef.nativeElement.value = initValue.replace(/[^0-9]*/g, "");
}
}
input
,使用伪指令的外观如下:
<input
type="tel"
[maxlength]="4"
[(ngModel)]="inputValue"
autocomplete="off"
onlyNumbers
/>
input
使用[(ngModel)]
将数据双向绑定到inputValue
。
如果我们尝试在input
中写一个字母,则第一个字母被接受。接下来的字母了。
我想[(ngModel)]
无法检测到本机元素的所有更改。我尝试使用Renderer2
通过以下方式设置本机元素值:
this.renderer.setValue(this.elementRef.nativeElement, initValue.replace(/[^0-9]*/g, ""));
但是它没有帮助。
stackblitz
示例可在此处找到:https://stackblitz.com/edit/ngmodel-question
问题是,为什么会这样?可以使用Renderer2
解决此问题,还是不应该进一步朝这个方向发展?