Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do onkeypress in angular 4

I am trying to implement a input tag that only allows numbers to be put in.

One way that I found work is the following

<input name="num" 
   type="number"
   pattern="[0-9]*" 
   placeholder="Enter new PIN" 
   onkeypress="return event.charCode >= 48 && event.charCode <= 57"
   title="Numbers only">

But I would like to change onkeypress for an angular function. Is there anything that can work similar?

I have tried (keyup), and (change) but neither work the same. They allow the key to be pressed then remove the number.

<input (keyup)="checkPin($event)" 
  type="number" 
  pattern="[0-9]*" 
  placeholder="Enter new PIN" 
  inputmode="numeric" 
  style="-webkit-text-security: disc;"></input>

Here is the TS function checkPin

checkPin($event: KeyboardEvent) {
  console.log($event)
  let value = (<HTMLInputElement>event.target).value;

  if ($event.target) {
    if (value == "") {
      value = value.slice(0, 0);
    }

    if (value.length > 4) {
      value = value.slice(0, 4)
    }
    (<HTMLInputElement>event.target).value = value.replace(/\D/g, '');
  }
}
like image 539
Whitecat Avatar asked Oct 25 '17 18:10

Whitecat


3 Answers

TS method:

keyPress(event: KeyboardEvent) {
    const pattern = /[0-9]/;
    const inputChar = String.fromCharCode(event).charCode);
    if (!pattern.test(inputChar)) {    
        // invalid character, prevent input
        event.preventDefault();
    }
}

HTML:

<input (keypress)="keyPress($event)" 
  type="number" 
  pattern="[0-9]*" 
  placeholder="Enter new PIN" 
  inputmode="numeric" 
  style="-webkit-text-security: disc;"></input>

Here the pattern in html is not needed because you are restricted to type another character than 0-9.

Good luck!

like image 112
Alan Grosz Avatar answered Sep 20 '22 18:09

Alan Grosz


For anyone else looking for another way of determining if a specific key is pressed (like the space key), you can use:

grabText(event){
    if(event.code === 'Space'){
        console.log('PRESSED SPACE');
        ...  
    }

}
like image 42
FiringBlanks Avatar answered Sep 19 '22 18:09

FiringBlanks


We should use KeyboardEvent instead of event as a type of the input parameter of keyPress

like image 44
Tarun Majumder Avatar answered Sep 17 '22 18:09

Tarun Majumder