I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[NumbersOnly]'
})
export class NumbersOnlyDirective {
// Allow decimal numbers and negative values
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['ArrowLeft', 'ArrowRight', 'Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) { }
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
The directive is utilized in input fields like so:
<input [(ngModel)]="sendLinkMobile" NumbersOnly type="text" id="mobile-num"
class="form-control m-no" placeholder="Mobile Number" requried minlength="10"
maxlength="10" aria-label="Recipient's username" aria-describedby="basic-addon2">
While the code works flawlessly on modern browsers, mobile devices, and tablets, it encounters issues when used on older versions of Chrome (49.xx and below), where the input fields fail to accept any values. I would appreciate any assistance in identifying and rectifying the problem.
Thank you in advance.