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

如何在Angular 5中实现动态切换的输入掩码功能?

在Angular 5中实现动态切换格式的输入掩码方案

当然可以实现这种聚焦显示纯数字、失焦显示带分隔符掩码的输入效果!我在Angular 5项目里处理过类似需求,下面给你两种靠谱的实现方式:

一、自定义指令(推荐,灵活性拉满)

这种方式完全可控,能精准匹配你想要的格式逻辑。核心思路是监听输入框的focus和blur事件,在不同状态下切换显示格式,同时始终保留纯数字的原始值用于表单提交。

步骤1:创建自定义指令

新建一个dynamic-mask.directive.ts文件,代码如下:

import { Directive, ElementRef, HostListener, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appDynamicMask]'
})
export class DynamicMaskDirective implements OnInit {
  // 存储原始纯数字值
  private rawNumericValue: string = '';
  // 掩码匹配规则:3位-2位-4位数字
  private maskRegex = /^(\d{3})(\d{2})(\d{4})$/;

  constructor(private el: ElementRef, private formControl: NgControl) {}

  ngOnInit() {
    // 初始化时如果表单已有值,先处理成掩码格式
    if (this.formControl.value) {
      this.rawNumericValue = this.formControl.value.replace(/\D/g, '');
      this.applyMaskFormat();
    }
  }

  // 聚焦时切换为纯数字显示
  @HostListener('focus') onInputFocus() {
    this.el.nativeElement.value = this.rawNumericValue;
  }

  // 失焦时恢复掩码格式
  @HostListener('blur') onInputBlur() {
    this.applyMaskFormat();
  }

  // 处理用户输入,只保留数字
  @HostListener('input', ['$event']) onUserInput(event: InputEvent) {
    const inputElement = event.target as HTMLInputElement;
    // 过滤非数字字符,更新原始值
    this.rawNumericValue = inputElement.value.replace(/\D/g, '');
    
    // 当前处于聚焦状态则显示纯数字,否则显示掩码
    if (document.activeElement === this.el.nativeElement) {
      inputElement.value = this.rawNumericValue;
    } else {
      this.applyMaskFormat();
    }

    // 更新表单控件的值为纯数字,方便后续提交/验证
    this.formControl.control.setValue(this.rawNumericValue);
  }

  // 应用掩码格式的私有方法
  private applyMaskFormat() {
    const matchResult = this.rawNumericValue.match(this.maskRegex);
    if (matchResult) {
      // 匹配成功则拼接成XXX-XX-1234格式
      this.el.nativeElement.value = `${matchResult[1]}-${matchResult[2]}-${matchResult[3]}`;
    } else {
      // 长度不够时显示原始数字
      this.el.nativeElement.value = this.rawNumericValue;
    }
  }
}

步骤2:在模块中声明指令

在你的模块文件(比如app.module.ts)中引入并声明这个指令:

import { DynamicMaskDirective } from './dynamic-mask.directive';

@NgModule({
  declarations: [
    // ...你的组件、管道等
    DynamicMaskDirective
  ],
  // ...其他配置
})
export class AppModule {}

步骤3:在模板中使用指令

在表单输入框上添加appDynamicMask指令即可:

<form [formGroup]="myForm">
  <input 
    type="text" 
    formControlName="idNumber" 
    appDynamicMask 
    placeholder="XXX-XX-1234"
  >
</form>

二、借助第三方库快速实现

如果不想写自定义代码,可以使用ngx-mask的兼容版本(Angular 5对应ngx-mask@7.0.0左右),通过配置动态掩码来实现:

  1. 安装依赖:
npm install ngx-mask@7.0.0 --save
  1. 在模块中导入NgxMaskModule:
import { NgxMaskModule } from 'ngx-mask';

@NgModule({
  imports: [
    // ...其他模块
    NgxMaskModule.forRoot()
  ]
})
export class AppModule {}
  1. 在模板中使用动态掩码:
    通过监听focus和blur事件切换掩码规则:
<input 
  type="text" 
  formControlName="idNumber"
  [mask]="isFocused ? '' : 'XXX-XX-1234'"
  (focus)="isFocused = true"
  (blur)="isFocused = false"
  placeholder="XXX-XX-1234"
>

然后在组件类中定义isFocused变量:

isFocused: boolean = false;

注意事项

  • 两种方案都会确保表单控件最终的值是纯数字,不会影响后续的数据处理。
  • 如果需要调整掩码格式(比如修改分隔符或数字长度),自定义指令只需要修改maskRegex和applyMaskFormat方法即可;第三方库则调整mask参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:05:02