Angular手机号掩码指令粘贴时功能异常,ngModel值与显示不一致
问题根源是当前指令只更新了输入框的视图层显示,没有把格式化后的值同步到ngModel绑定的底层数据模型上,且缺少对粘贴事件的监听处理,所以出现了视图和绑定值不一致的情况。
修复后的完整代码如下:
import { NgControl } from '@angular/forms'; import { HostListener, Directive } from '@angular/core'; @Directive({ selector: '[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 || event.srcElement).value, true); } // 新增粘贴事件监听,处理粘贴场景 @HostListener('paste', ['$event']) onPaste(event: ClipboardEvent) { event.preventDefault(); const pastedText = event.clipboardData?.getData('text') || ''; this.onInputChange(pastedText, false); } onInputChange(event: string, backspace: boolean) { 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); // 同步更新ngModel绑定的底层值,emitEvent设为false避免触发循环事件 this.ngControl.control?.setValue(newVal, { emitEvent: false }); } }
核心修改点:
- 新增粘贴事件的监听逻辑,主动拦截粘贴内容做格式化处理,避免粘贴操作绕过原有输入监听逻辑
- 之前仅调用
writeValue只会更新输入框的显示内容,新增的setValue调用会把格式化后的值同步到ngModel底层模型,保证视图和绑定值完全一致 - 修复了原代码里残留的无效代码片段和HTML转义导致的
&&符号错误
内容的提问来源于stack exchange,提问作者Rishav Harsh
相关产品推荐
相关产品推荐

