angular - 如何在 HostListener 输入操作中防止默认()

标签 angular angular5 angular-directive

我正在尝试编写一个指令来限制用户在输入文本控件中仅输入数字字符。

@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 />

但是它不起作用,有人遇到过这个问题吗?

最佳答案

使用键盘事件类型 - keydownkeypress:

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

关于angular - 如何在 HostListener 输入操作中防止默认(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50022255/

相关文章:

json - Angular HttpClient 错误处理困难

Angular HttpClient不发送POST,它发送OPTIONS

mongodb - Angular 5 + Material 设计 : <mat-select> how to set the default value?

javascript - 如何在 Angular 指令中调用我自己的函数?

angularjs - 指令未加载作用域变量

Angular 2.0 版本 : Pipes and Directives are not properties of @Component anymore

angular - 以编程方式检查来自 TypeScript 的 ionic radio

javascript - 难以通过网络蓝牙连接热敏打印机

css - Angular 5 material flex-layout fxLayoutAlign ="space-evenly center"不工作

angular - 指令绑定(bind)在规范文件中不起作用