How to only allow text in angular 9 ?
Table of Contents
keydown vs keyup ?
If you print event.target.value then keydown event will give previous character only, so it will be quiet difficult for you to perform some validations with keydown – event.target.value.
If you press, “ngd” then keydown prints “ng” only on press of d value.
But keyup prints “ngd” only when d character is pressed.
So the winner for this use case is keyup
In angular template:
(keyup)="allowOnlyText"
In angular component:
allowOnlyText(event): boolean{
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 90 && charCode < 97 ) {
return false;
}
if(charCode < 65 || charCode > 122){
return false;
}
return true;
}
How to check whether the string contains number or not ?
isTextOnly(event): boolean {
if(this.checkNameContainsNumber(event.target.value)){
return false;
}
return true;
}
isContainsNumbers(value:string):boolean{
for(var temp=0;temp<value.length;temp++){
var numberValues = value.charCodeAt(temp);
if(numberValues>=48 && numberValues<=57){
console.log("number is found, so returning true");
return true;
}
}
return false;
}