如何让Angular Material数字输入框仅显示纯数字键盘(适配手机号/OTP)
解决方案:实现纯数字键盘的手机号与OTP输入
一、手机号输入优化
替换原有的type="number"配置,改用type="tel"配合输入限制属性,同时添加实时输入过滤逻辑,确保唤起纯数字键盘且仅允许输入数字:
模板代码
<mat-form-field class="col-12" appearance="outline" subscriptSizing="dynamic"> <mat-label>Mobile Number</mat-label> <input type="tel" matInput formControlName="MobileNumber" inputmode="numeric" pattern="[0-9]*" (input)="restrictToNumbers($event)" > <span matPrefix style="font-size: 1rem; position: relative; left: 5px"> +91 </span> <button mat-icon-button matSuffix> <mat-icon>edit</mat-icon> </button> </mat-form-field>
组件类逻辑
在组件TS文件中添加输入过滤方法:
restrictToNumbers(event: Event): void { const inputEl = event.target as HTMLInputElement; // 移除所有非数字字符 inputEl.value = inputEl.value.replace(/[^0-9]/g, ''); }
关键说明
type="tel":专门针对电话号码输入设计,移动端会优先唤起纯数字键盘inputmode="numeric":明确告知浏览器需唤起数字输入键盘,进一步确保纯数字布局pattern="[0-9]*":用于HTML5原生表单验证,标记输入内容必须为数字(input)事件过滤:实时移除粘贴或误输入的非数字字符,确保输入框内容纯净
二、OTP输入场景适配
针对OTP的多位单字符输入需求,可采用多输入框布局,结合自动聚焦切换与数字限制:
模板代码
<div class="d-flex gap-2"> <mat-form-field *ngFor="let _ of Array(6)" class="otp-field"> <input type="tel" matInput inputmode="numeric" pattern="[0-9]" maxlength="1" (input)="jumpToNextOtpInput($event)" (keydown.backspace)="jumpToPrevOtpInput($event)" > </mat-form-field> </div>
组件类逻辑
添加自动聚焦切换方法:
jumpToNextOtpInput(event: Event): void { const currentInput = event.target as HTMLInputElement; if (currentInput.value.length === 1) { const nextInput = currentInput.nextElementSibling?.querySelector('input') as HTMLInputElement; nextInput?.focus(); } } jumpToPrevOtpInput(event: KeyboardEvent): void { const currentInput = event.target as HTMLInputElement; if (!currentInput.value) { const prevInput = currentInput.previousElementSibling?.querySelector('input') as HTMLInputElement; prevInput?.focus(); } }
样式优化(可选)
添加CSS让OTP输入框更紧凑:
.otp-field { width: 60px; } .otp-field input { text-align: center; }
三、表单验证补充
在表单控件初始化时添加验证规则,确保输入格式符合要求:
// 手机号验证:10位数字 this.form = this.fb.group({ MobileNumber: ['', [Validators.required, Validators.pattern(/^[0-9]{10}$/)]] }); // OTP验证:可通过表单组或自定义验证器检查所有输入框内容
内容的提问来源于stack exchange,提问作者ErMapsh
相关产品推荐
相关产品推荐

