Whitecat
Whitecat

Reputation: 4020

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, '');
  }
}

Upvotes: 25

Views: 129124

Answers (4)

Alan Grosz
Alan Grosz

Reputation: 1325

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!

Upvotes: 49

Thilina Koggalage
Thilina Koggalage

Reputation: 1084

To make a input field number only, you can do this. So you can use onkeypress for another function.

 <input type="text"
    onkeydown="javascript: return event.keyCode === 8 || 
                                  event.keyCode === 46 ?
                                  true : !isNaN(Number(event.key))"/>

Upvotes: 3

Tarun Majumder
Tarun Majumder

Reputation: 99

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

Upvotes: 1

FiringBlanks
FiringBlanks

Reputation: 2084

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');
        ...  
    }

}

Upvotes: 1

Related Questions