In our current project, we are utilizing Angular 17 in conjunction with Reactive forms. A custom directive has been implemented to format the output to the US phone number format `111-222-3333`. However, an issue has arisen where when a number is copied into the field, the field becomes formatted but the validator still detects it as invalid.
Here is the HTML Code:
<input matInput phoneFormatterDirective placeholder="Enter Phone" formControlName="phone" class="inputEntry">
And the Typescript Code:
phone: new FormControl(null, [Validators.pattern('^[0-9]{3}-[0-9]{3}-[0-9]{4}$')])
Below is the Custom Directive Code:
import {Directive, HostListener} from '@angular/core';
@Directive({
selector: '[phoneFormatterDirective]'
})
export class PhoneFormatterDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
event.preventDefault();
const input = event.target as HTMLInputElement;
// Formatting logic here
}
}
When attempting to paste a number like `(555) 123-1234`, it gets converted to `555-123-1234` but still shows as invalid. A workaround is deleting a character and re-entering it manually, which is a peculiar behavior.