在 Angular 中格式化电话号码输入 [英] Formatting Phone Number Input In Angular

查看:18
本文介绍了在 Angular 中格式化电话号码输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了许多在 Angularjs 中格式化电话号码输入字段的解决方案,但我在 Angular 7 上找不到任何内容.我真正想要的是让用户在文本字段中键入以下内容:

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 the following in the textfield:

123456789

文本字段将输入格式化为:

and for the textfield to format the input as:

(123) 456-789

(123) 456-789

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

how can I go about doing this? I have found the following regex to validate it:

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

推荐答案

您可以使用 Phone Mask Directive 处理此问题,如下所示,

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 演示

这篇关于在 Angular 中格式化电话号码输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆