You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:启用该属性时,组件会对输入字符进行掩码占位符的实时渲染与替换处理,而@字符被误识别为掩码体系中的特殊占位符相关字符,触发了内部的过滤拦截机制。其他特殊字符(如~#$%&)不在这个特殊判定范围内,因此不受影响。

可行解决办法

  1. 转义正则中的@字符
    修改自定义正则模式,将@转义(强制组件将其识别为普通输入字符):

    this.customPatterns = { B: { pattern: new RegExp('[a-zA-Z0-9\\@$%&#~]') } };
    
  2. 手动处理输入事件
    通过监听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为实际的表单组变量名。

  3. 升级ngx-mask版本
    检查ngx-mask的官方更新日志,升级到修复该bug的最新兼容版本(需确保版本与Angular 17兼容)。

内容的提问来源于stack exchange,提问作者stormbreakR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:56:26