我正在尝试编写一个指令来限制用户在输入文本控件中仅输入数字字符。
@Directive({
selector: '[numericControl]'
})
export class NumericControlDirective {
contructor(
private el: ElementRef,
) {}
@HostListener('input', ['$event'])
onInput(e: any) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}
}
用法
<input type="text" placeholder="Volume" numericControl />
但是它不起作用,有人遇到过这个问题吗?
最佳答案
使用键盘事件类型 - keydown
或 keypress
:
@HostListener('keydown', ['$event'])
onInput(e: any) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}
关于angular - 如何在 HostListener 输入操作中防止默认(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50022255/