如何在 HostListener 输入操作中防止默认()
How to preventDefault() in HostListener Input action
我正在尝试编写一个指令来限制用户在输入文本控件中仅输入数字字符。
@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();
}
}
您也可以使用
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent>event;
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}
我正在尝试编写一个指令来限制用户在输入文本控件中仅输入数字字符。
@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();
}
}
您也可以使用
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent>event;
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}