Even though replicating this issue is challenging, a reliable solution is to simply replace the input value. Change the input element type to HTMLInputElement
first. Then apply the replacement in one, two, or all three of the following locations:
inputElement: HTMLInputElement;
constructor(public el: ElementRef) {
this.inputElement = el.nativeElement;
}
@HostListener('keydown', ['$event'])
onKeyDown(e: KeyboardEvent) {
if (
this.navigationKeys.indexOf(e.key) > -1 || // Allow: navigation keys: backspace, delete, arrows etc.
(e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
(e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
(e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
(e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
(e.key === 'a' && e.metaKey === true) || // Allow: Cmd+A (Mac)
(e.key === 'c' && e.metaKey === true) || // Allow: Cmd+C (Mac)
(e.key === 'v' && e.metaKey === true) || // Allow: Cmd+V (Mac)
(e.key === 'x' && e.metaKey === true) // Allow: Cmd+X (Mac)
) {
// Let it continue, no action needed.
this.inputElement.value = this.inputElement.value.replace(/\D/g, '');
return;
}
// Check for number and block keypress.
if (
(e.shiftKey || e.key < '0' || e.key > '9') &&
(e.key < 'numpad 0' || e.key > 'numpad 9')
) {
e.preventDefault();
}
this.inputElement.value = this.inputElement.value.replace(/\D/g, '');
}
@HostListener('keyup', ['$event'])
onKeyUp(e: KeyboardEvent) {
this.inputElement.value = this.inputElement.value.replace(/\D/g, '');
}