格式化 Phone 输入的数字 Angular

Formatting Phone Number Input In Angular

我在 Angularjs 中看到了很多格式化 phone 数字输入字段的解决方案,但我在 Angular 上找不到任何东西 7. 我本质上想要的是用户在文本字段中键入以下内容:

123456789

并将文本字段的输入格式设置为:

(123) 456-789

我该怎么做呢?我找到了以下正则表达式来验证它:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

您可以使用 Phone 掩码指令处理此问题,如下所示,

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})/, '()');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '() ');
    } else if (newVal.length <= 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '() -');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '() -');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

STACKBLITZ DEMO

您可以轻松安装 ngx-mask 包,然后像这样指定您理想的面具:

mask="(000) 000-000"

< input type="text" mask="(000) 000-000" />