How to preventDefault() in HostListener Input action

末鹿安然 提交于 2019-12-23 13:05:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!