I have refered the link: Input mask fields in Angular2 forms and I was able to mask input field like: (123) 456-7890.
Please find updated code below:
Directive TS File:
@Directive({
selector: '[appPhoneMasking]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(keydown.backspace)': 'onInputChange($event.target.value, true)'
}
})
export class PhoneMaskingDirective {
constructor(public model: NgControl) {}
onInputChange(event, backspace) {
// remove all mask characters (keep only numeric)
var newVal = event.replace(/\D/g, '');
if (backspace) {
newVal = newVal.substring(0, newVal.length - 1);
}
// don't show braces for empty value
if (newVal.length == 0) {
newVal = '';
}
// don't show braces for empty groups at the end
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 {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
}
if(newVal.length > 14) {
newVal = newVal.slice(0, 14);
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
}
}
And HTML file:
<form [formGroup]="addUser" (ngSubmit)="submitUser()">
<input type="text" class="form-control" formControlName="user_phone" appPhoneMasking>
</form>
Component File:
this.addUser= this._formBuilder.group({
user_phone: new FormControl('', [Validators.maxLength(14)]),
});
I have two issue which I am trying to solve but no success. These are:
- When I press backspace two character are deleted from the string.
- Also I want only 14 characters to be in phone number. As soon as I type 15 character the input field is updated. But the form is not updated. I get error that my form is not valid.
Please let me know how can I fix these issues.