Phone mask directive is not working when pasting phone number in input box

Viewed 79

I have written a directive which masks a phone number in the format (888) 888-8888 , the directive is working fine when I am entering the number but not working when I am pasting number in the input box, however in the is the input bot is coming as expected (888) 888-8888 but in the ngModel it is coming as 88888888888

import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appPhoneMask]',
})

export class PhoneMaskDirective {

  constructor(public ngControl: NgControl) {
  }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }`enter code here`

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange((event.target || event.srcElement).value, true);
  }


  onInputChange(event, backspace) {
    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');
    } else {
      newVal = newVal.substring(0, 10);enter code here
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
0 Answers
Related