问题
Im trying to write a directive that limit user to input numeric only characters in the input text control.
@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();
}
}
}
Usage
<input type="text" placeholder="Volume" numericControl />
But it doesn't work, Anyone came across this issue?
回答1:
Use Keyboard event type - keydown
or keypress
:
@HostListener('keydown', ['$event'])
onInput(e: any) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}
回答2:
You can also use
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent>event;
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
}
来源:https://stackoverflow.com/questions/50022255/how-to-preventdefault-in-hostlistener-input-action