【问题标题】:To format a telephone number in Angular在 Angular 中格式化电话号码
【发布时间】:2020-04-29 08:24:01
【问题描述】:

我正在尝试创建一个指令,将电话号码从 1234567890 格式化为 (123) 456-7890。 指令代码如下:

import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[formControlName][appPhoneMask]',
})
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);
  }
}

我使用此指令面临的问题是,当输入第一个数字时,它会将数字放在括号之间,但在输入第二个数字时出现错误 无法读取 null 的属性“替换” 在 PhoneMaskDirective.onInputChange

请提出一些解决方案或替代此方法。

【问题讨论】:

    标签: angularjs angular number-formatting


    【解决方案1】:

    Manish,检查下面的代码 sn-p,只需将字符串传递给“phoneFormat”方法即可获得所需的输出。

    function phoneFormat (value) {
                    var numbers = value && value.replace(/-/g,"");
                    var matches = numbers && numbers.match(/^(\d{3})(\d{3})(\d{4})$/);
                    
                    if (matches) {
                        return '('+matches[1] + ") " + matches[2] + "-" + matches[3];
                    }
    
                    return undefined;
                }
    const phoneNumber = phoneFormat("1234567890");            
    console.log(phoneNumber);            

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多