Angular17中ngx-mask开启showMaskTyped后无法输入@的问题咨询
ngx-mask@17.0.4中showMaskTyped导致@无法输入的问题解析
问题场景
在Angular 17项目中使用ngx-mask@17.0.4,输入字段代码如下:
<input id="otp" class="form-control" name="otp" formControlName="otp" [dropSpecialCharacters]="false" [patterns]="customPatterns" mask="BBBBBBBBBB" [showMaskTyped]="true">
自定义正则模式代码:
this.customPatterns = { B: { pattern: new RegExp('[a-zA-Z0-9@$%&#~]') } };
当前问题:输入框可正常接收大小写字母、数字及~#$%&等特殊字符,但无法输入@;移除showMaskTyped属性后,@可正常输入,但业务需要保留该功能。
原因分析
这是ngx-mask在showMaskTyped模式下的内部逻辑bug:启用该属性时,组件会对输入字符进行掩码占位符的实时渲染与替换处理,而@字符被误识别为掩码体系中的特殊占位符相关字符,触发了内部的过滤拦截机制。其他特殊字符(如~#$%&)不在这个特殊判定范围内,因此不受影响。
可行解决办法
转义正则中的@字符
修改自定义正则模式,将@转义(强制组件将其识别为普通输入字符):this.customPatterns = { B: { pattern: new RegExp('[a-zA-Z0-9\\@$%&#~]') } };手动处理输入事件
通过监听input事件,手动保留输入的@字符:<input id="otp" class="form-control" name="otp" formControlName="otp" [dropSpecialCharacters]="false" [patterns]="customPatterns" mask="BBBBBBBBBB" [showMaskTyped]="true" (input)="handleOtpInput($event)">handleOtpInput(event: Event) { const inputEl = event.target as HTMLInputElement; const ctrl = this.yourFormGroup.get('otp'); if (ctrl && inputEl.value.includes('@')) { ctrl.setValue(inputEl.value); } }注意替换代码中的
yourFormGroup为实际的表单组变量名。升级ngx-mask版本
检查ngx-mask的官方更新日志,升级到修复该bug的最新兼容版本(需确保版本与Angular 17兼容)。
内容的提问来源于stack exchange,提问作者stormbreakR
相关产品推荐
相关产品推荐

