I am currently facing an issue with my phone mask directive that is designed to accept US format phone numbers. The problem arises when I try to clear the input by deleting one character at a time using the backspace key, as the value in the input field doesn't get emptied. This issue came to light only after I logged the input value of the form.
Interestingly, if I clear the entire input at once, it does get emptied. However, clearing the input one character at a time always leaves one digit behind.
https://i.sstatic.net/Tg6HMm.png
Does anyone know how to ensure the input value gets cleared when the form value is empty?
For reference, I have provided a functional example using StackBlitz. Can someone assist me with this issue?
Here is my Directive:
export class PhoneMaskDirective {
constructor(public ngControl: NgControl) {}
@HostListener("ngModelChange", ["$event"])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener("keydown.backspace", ["$event"])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
onInputChange(event, backspace) {
if (event == null) {
return "";
}
let newVal = event.replace(/\D/g, "");
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
newVal = "";
} else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, "($1)");
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, "($1) $2");
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, "($1) $2-$3");
}
this.ngControl.valueAccessor.writeValue(newVal);
}
}