如何实现输入框输入时每三位数字掩码,点击提交展示原始未掩码值
Angular 输入框实时数字掩码实现方案
核心需求
当前仅能在blur事件触发时对输入数字做掩码,需要实现两个核心能力:
- 输入过程中实时对展示内容做掩码处理
- 点击提交按钮时可获取并展示用户输入的原始未掩码值
实现思路
通过两个变量做存储隔离,避免原始值和展示值互相干扰:
- 原始值变量:不对用户展示,仅用来存储用户输入的完整内容,提交时直接取用即可
- 掩码展示变量:实时处理后绑定到输入框的
value,仅作用户可见的展示使用
核心代码实现
组件逻辑代码(app.component.ts)
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // 存储用户输入的原始未掩码值 rawInputValue = ''; // 绑定到输入框的掩码展示控制器 maskedInputControl = new FormControl(''); // 提交后展示的原始值 submittedRawValue = ''; onInput(event: Event): void { const inputEle = event.target as HTMLInputElement; const currentInput = inputEle.value; const lastChar = currentInput.slice(-1); // 仅允许数字输入,可根据业务需求调整校验规则 if (!/^\d$/.test(lastChar) && currentInput.length > this.rawInputValue.length) { inputEle.value = this.getMaskedValue(); return; } // 同步更新原始值 if (currentInput.length > this.rawInputValue.length) { this.rawInputValue += lastChar; } else if (currentInput.length < this.rawInputValue.length) { // 处理退格、删除操作 this.rawInputValue = this.rawInputValue.slice(0, -1); } // 实时更新输入框展示的掩码内容 this.maskedInputControl.setValue(this.getMaskedValue(), { emitEvent: false }); } // 掩码规则可自定义,当前示例为末尾4位明文,其余内容掩码 private getMaskedValue(): string { const length = this.rawInputValue.length; if (length <= 4) { return '*'.repeat(length); } return '*'.repeat(length - 4) + this.rawInputValue.slice(-4); } onSubmit(): void { // 提交时直接取用存储的原始值即可 this.submittedRawValue = this.rawInputValue; } }
模板代码(app.component.html)
<input type="text" [formControl]="maskedInputControl" (input)="onInput($event)" placeholder="请输入数字" > <button (click)="onSubmit()">提交</button> <div *ngIf="submittedRawValue"> 提交的原始值:{{ submittedRawValue }} </div>
自定义调整说明
- 若需要修改掩码规则(比如手机号前3后4明文、银行卡号前6后4明文),仅需修改
getMaskedValue方法内的逻辑即可 - 若需要支持数字以外的字符输入,修改
onInput方法内的输入校验正则即可 - 已经兼容退格、删除等操作的边界情况,不会出现原始值和展示值不同步的问题
内容的提问来源于stack exchange,提问作者niharika chilukuri
相关产品推荐
相关产品推荐

