Angular中无法关闭ngx-otp-input的OTP自动补全功能
解决ngx-otp-input组件无法关闭OTP自动补全的问题
问题背景
尝试了以下方法均无法关闭ngx-otp-input的OTP自动补全:
- 给组件设置
autocomplete="off" - 设置
autocomplete="new-password" - 通过模板变量修改组件DOM的
autocomplete属性
现有代码:
HTML
<ngx-otp-input #disableautocomplete class="mobile-otp-ui mobile-otp-ui-otp" id="otp-1" [config]="otpInputConfig2" (otpChange)="handleOtpChange2($event)" (fill)="handleFillEvent2($event)" name="mobileotp" autocomplete="off" > </ngx-otp-input>
TypeScript
@ViewChild('disableautocomplete', { read: ElementRef }) disableautocomplete; ngAfterViewInit(){ this.disableautocomplete.nativeElement.autocomplete ='off'; }
可行解决方案
ngx-otp-input组件内部会渲染多个独立的<input>元素,直接给组件根元素设置autocomplete属性不会传递到内部输入框,需要针对每个内部input做处理:
方法1:遍历内部输入框设置禁用属性
修改ngAfterViewInit方法,找到组件内所有input元素,逐个配置禁用自动填充的属性:
@ViewChild('disableautocomplete', { read: ElementRef }) disableautocomplete; ngAfterViewInit() { const inputs = this.disableautocomplete.nativeElement.querySelectorAll('input'); inputs.forEach((input: HTMLInputElement) => { // 设置浏览器不识别的autocomplete值,避免被忽略 input.autocomplete = 'nope'; // 强制设置属性(部分浏览器需要显式setAttribute) input.setAttribute('autocomplete', 'nope'); // 添加readonly并结合焦点事件,阻止自动填充同时不影响输入 input.setAttribute('readonly', 'readonly'); input.addEventListener('focus', () => input.removeAttribute('readonly')); input.addEventListener('blur', () => input.setAttribute('readonly', 'readonly')); }); }
方法2:使用自定义模板渲染输入框
如果组件支持自定义模板(需确认ngx-otp-input版本是否支持),直接手动渲染每个OTP输入框并配置属性:
<ngx-otp-input [config]="otpInputConfig2" (otpChange)="handleOtpChange2($event)" (fill)="handleFillEvent2($event)"> <ng-template ngx-otp-input-tmp let-index="index"> <input type="text" autocomplete="nope" readonly (focus)="$event.target.removeAttribute('readonly')" (blur)="$event.target.setAttribute('readonly', 'readonly')" /> </ng-template> </ngx-otp-input>
方法3:添加随机name属性
部分浏览器会根据name属性匹配自动填充数据,给每个内部input设置随机name可以避免匹配:
inputs.forEach((input: HTMLInputElement, index: number) => { input.name = `otp-random-${index}-${Math.random().toString(36).slice(2)}`; input.autocomplete = 'off'; });
内容的提问来源于stack exchange,提问作者Shreya Bhanot
相关产品推荐
相关产品推荐

