Javascript Angular 8中的电话掩码指令
我有这个电话掩码指令,它接受美国格式的电话号码。但是,当我通过逐个单击backspace清除输入中的内容时,输入表单中的值不会被清空。直到我记录了表单的输入值,我才意识到这个问题 而且,当我立即清除输入表单时,它正在被清空。但是,按表单值一个接一个地清除返回空间总是会留下一个值 当表单值为空时,如何清除输入值 我使用创建了一个工作示例。有人能帮忙吗 指令Javascript Angular 8中的电话掩码指令,javascript,angular,regex,typescript,angular-directive,Javascript,Angular,Regex,Typescript,Angular Directive,我有这个电话掩码指令,它接受美国格式的电话号码。但是,当我通过逐个单击backspace清除输入中的内容时,输入表单中的值不会被清空。直到我记录了表单的输入值,我才意识到这个问题 而且,当我立即清除输入表单时,它正在被清空。但是,按表单值一个接一个地清除返回空间总是会留下一个值 当表单值为空时,如何清除输入值 我使用创建了一个工作示例。有人能帮忙吗 指令 export class PhoneMaskDirective { constructor(public ngControl: NgCo
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) {
if (event == null) {
return "";
}
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");
}
this.ngControl.valueAccessor.writeValue(newVal);
}
}
导出类PhoneMaskDirective{
构造函数(公共ngControl:ngControl){}
@HostListener(“ngModelChange”,[“$event”])
onModelChange(事件){
此.onInputChange(事件,false);
}
@HostListener(“keydown.backspace”,[“$event”])
keydownBackspace(事件){
此.onInputChange(event.target.value,true);
}
onInputChange(事件,退格){
如果(事件==null){
返回“”;
}
让newVal=event.replace(/\D/g,“”);
if(backspace&&newVal.length建议使用@HostBindings
和@HostListeners
而不是主机
属性
删除主机
并添加@HostListener
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
当输入值length==0且valueAccessor.writevalue在此处不起作用时,您的问题可能被设置为null值
你能换这个吗
this.ngControl.control.setValue(null);
而不是
this.ngControl.valueAccessor.writeValue(null);
参考:太好了,就是这样!