showing results for - "angular format phone number while typing"
Luigi
24 Jan 2018
1export class PhoneMaskDirective {
2
3  constructor(public ngControl: NgControl) { }
4
5  @HostListener('ngModelChange', ['$event'])
6  onModelChange(event) {
7    this.onInputChange(event, false);
8  }
9
10  @HostListener('keydown.backspace', ['$event'])
11  keydownBackspace(event) {
12    this.onInputChange(event.target.value, true);
13  }
14
15
16  onInputChange(event, backspace) {
17    let newVal = event.replace(/\D/g, '');
18    if (backspace && newVal.length <= 6) {
19      newVal = newVal.substring(0, newVal.length - 1);
20    }
21    if (newVal.length === 0) {
22      newVal = '';
23    } else if (newVal.length <= 3) {
24      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
25    } else if (newVal.length <= 6) {
26      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
27    } else if (newVal.length <= 10) {
28      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
29    } else {
30      newVal = newVal.substring(0, 10);
31      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
32    }
33    this.ngControl.valueAccessor.writeValue(newVal);
34  }
35}
36