PrimeNG InputOtp开启integerOnly=true时Num Lock关闭下数字小键盘失效
PrimeNG InputOtp integerOnly 属性导致 Num Lock 关闭时小键盘失效问题
当给 PrimeNG 的 InputOtp 组件设置 [integerOnly]="true" 后,若键盘右侧数字小键盘处于 Num Lock 关闭状态,输入小键盘上的数字会完全失效。
问题复现代码
<div class="card flex justify-content-center"> <p-inputOtp [(ngModel)]="value" [integerOnly]="true"></p-inputOtp> </div>
export class InputOtpIntegerOnlyDemo { value : any }
问题原因
integerOnly 的默认实现仅拦截了非数字字符的输入,但没有考虑 Num Lock 关闭时,小键盘的数字键会映射为功能键(比如 1→End、2→Down 等),这些功能键的键码不在默认的数字允许范围内,导致输入被组件拦截。
解决方案:自定义指令修复
可以通过自定义指令监听键盘事件,将 Num Lock 关闭时小键盘的功能键映射为对应数字,手动触发组件的输入逻辑:
- 创建修复指令
import { Directive, HostListener } from '@angular/core'; import { InputOtp } from 'primeng/inputotp'; @Directive({ selector: 'p-inputOtp[integerOnly][fixNumLock]' }) export class FixNumLockDirective { constructor(private inputOtp: InputOtp) {} @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) { // Num Lock关闭时小键盘功能键与数字的映射 const numpadKeyMap: Record<string, string> = { '35': '1', '40': '2', '34': '3', '37': '4', '12': '5', '39': '6', '36': '7', '38': '8', '33': '9', '45': '0' }; if (this.inputOtp.integerOnly && numpadKeyMap[event.keyCode]) { event.preventDefault(); const activeInput = document.activeElement as HTMLInputElement; if (activeInput?.parentElement?.classList.contains('p-inputotp-input')) { // 更新组件值 const newValue = this.inputOtp.value ? [...this.inputOtp.value] : []; newValue[this.inputOtp.activeIndex] = numpadKeyMap[event.keyCode]; this.inputOtp.writeValue(newValue.join('')); // 自动跳转到下一个输入框 this.inputOtp.moveToNext(this.inputOtp.activeIndex); } } } }
- 在组件中使用指令
<div class="card flex justify-content-center"> <p-inputOtp [(ngModel)]="value" [integerOnly]="true" fixNumLock></p-inputOtp> </div>
这个指令会监听小键盘在 Num Lock 关闭时的功能键输入,将其转换为对应数字并更新到 OTP 输入框中,同时保持组件原有的自动跳转逻辑。
内容的提问来源于stack exchange,提问作者sanjai
相关产品推荐
相关产品推荐

