如何在HostListener输入操作中防止Default()

Roe*_*oel 4 angular-directive angular angular5

我试图写一条指令,限制用户只能在输入文本控件中输入数字字符。

@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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

用法

<input type="text" placeholder="Volume" numericControl />
Run Code Online (Sandbox Code Playgroud)

但这是行不通的,有人遇到过这个问题吗?

Jul*_*ius 5

使用键盘事件类型- keydownkeypress

@HostListener('keydown', ['$event'])
onInput(e: any) {
  if (e.which < 48 || e.which > 57) {
      e.preventDefault();
  }
}
Run Code Online (Sandbox Code Playgroud)