Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Roel Avatar asked Apr 25 '18 12:04

Roel


1 Answers

Use Keyboard event type - keydown or keypress:

@HostListener('keydown', ['$event'])
onInput(e: any) {
  if (e.which < 48 || e.which > 57) {
      e.preventDefault();
  }
}
like image 166
Julius Dzidzevičius Avatar answered Nov 08 '22 01:11

Julius Dzidzevičius