I work with angular 7.
I have this code which is working in desktop with chrome browser.
with this code I can enter only numbers and not more than 4 number.
html code :
<div class="col-12 col-md-6">
<div class="form__group btm">
<label class="form__label">
numidentity :
</label>
<input
class="form__input validation-field"
[(ngModel)]="this.numidentity"
(keypress)="keyPressNumbersIdentity($event)"
placeholder=""
type="text" >
</div>
</div>
typescript code :
keyPressNumbersIdentity(event) {
var charCode = (event.which) ? event.which : event.keyCode;
// Only Numbers 0-9
if ((charCode < 48 || charCode > 57)) {
event.preventDefault();
return false;
} else {
if (event.target.value.length >4) {
event.preventDefault();
return false;
}
else
{
return true;
}
}
}
but when I test the same html page in mobile android chrome browser the (keypress) events not working meaning I can enter characters not only number and more then 4 number.
keypress
events are deprecated and may not work consistently across devices, especially on mobile browsers. A better approach would be to use the keydown
, input
, or beforeinput
events.
...
(input)="keyPressNumbersIdentity($event)"
...
or:
...
(keydown)="keyPressNumbersIdentity($event)"
...
3
HTML
<div class="col-12 col-md-6">
<div class="form__group btm">
<label class="form__label">
numidentity:
</label>
<input
class="form__input validation-field"
[(ngModel)]="numidentity"
(input)="onInputNumbersIdentity($event)"
placeholder=""
type="text">
</div>
</div>
TS
import { Component} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
numidentity:string;
onInputNumbersIdentity(event: Event) {
const inputElement = event.target as HTMLInputElement;
// Replace non-numeric characters
inputElement.value = inputElement.value.replace(/[^0-9]/g, '');
// Prevent entering more than 4 numbers (though maxlength will handle this too)
if (inputElement.value.length > 4) {
inputElement.value = inputElement.value.slice(0, 4);
}
// Update the ngModel manually if needed (optional, if [(ngModel)] is used)
this.numidentity = inputElement.value;
}
}