Search code examples
angularangular5angular-directive

How to preventDefault() in HostListener Input action


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?


Solution

  • Use Keyboard event type - keydown or keypress:

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