如何在 HostListener Input 操作中防止 Default() [英] How to preventDefault() in HostListener Input action

查看:24
本文介绍了如何在 HostListener Input 操作中防止 Default()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

用法

<input type="text" placeholder="Volume" numericControl />

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

But it doesn't work, Anyone came across this issue?

推荐答案

Use Keyboard event type - keydown or keypress:

Use Keyboard event type - keydown or keypress:

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

这篇关于如何在 HostListener Input 操作中防止 Default()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆