How to do onkeypress in angular 4
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');
...
}
}
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!