Formatting Phone Number Input In Angular

后端 未结 2 785
盖世英雄少女心
盖世英雄少女心 2021-01-14 01:10

I have seen many solutions to formatting a phone number input field in Angularjs, but I cannot find anything on Angular 7. What I essentially want is for the user to type th

相关标签:
2条回答
  • 2021-01-14 01:23

    You can handle this with a Phone Mask Directive as follows,

    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) {
        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);
          newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
        }
        this.ngControl.valueAccessor.writeValue(newVal);
      }
    }
    

    STACKBLITZ DEMO

    0 讨论(0)
  • 2021-01-14 01:31

    You can easily install ngx-mask package and then specify your ideal mask like this:

    mask="(000) 000-000"
    
    < input type="text" mask="(000) 000-000" />
    
    0 讨论(0)
提交回复
热议问题