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, '');
}
}
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!
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');
...
}
}
We should use KeyboardEvent
instead of event as a type of the input parameter of keyPress
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With