我正在尝试创建一条指令,将电话号码的格式从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
请提出一些解决方案或替代此方法的方法。
Manish,请检查以下代码段,只需将字符串传递给“ 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);