Angular TypeScript12中如何实现输入内容回车后才触发Bootstrap弹窗
问题根因
- 输入框同时绑定了Bootstrap原生触发弹窗的
data-toggle="modal"data-target="#exampleModal"属性,这部分属性会绕过Angular自定义逻辑直接触发弹窗 show变量初始化值为true,页面加载完成后modal默认被添加show类直接展示- 表单值监听加了1秒防抖,按下回车时可能还未拿到最新的输入值
Search方法中引用的codeuser变量未定义,会触发运行时报错showModal为直接取反逻辑,未做输入非空校验,只要触发就会切换弹窗状态
修正方案
1. 输入框代码
移除Bootstrap原生触发弹窗的属性,仅保留回车触发事件:
<input (keyup.enter)="Search()" [formControl]="firstNameControl" type="text">
2. 弹窗Modal代码
补充display样式控制,适配Bootstrap原生modal的显隐逻辑:
<div class="modal" [class.show]="show" [style.display]="show ? 'block' : 'none'" id="exampleModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <!-- 弹窗主体内容省略 --> </div> </div>
3. TypeScript业务代码
修正初始值、移除不必要的防抖逻辑、增加非空校验:
show: boolean = false; // 初始值改为false,默认不展示弹窗 firstNameControl = new FormControl(); code!:string; ngOnInit(): void { this.firstNameControl.valueChanges.subscribe(newValue => { this.code= newValue }); } showModal() { this.show = !this.show; } Search() { // 直接取表单最新值规避监听延迟,增加非空校验 const inputValue = this.firstNameControl.value?.trim(); if (!inputValue) return; this.code = inputValue; console.log(this.code); this.showModal(); }
内容的提问来源于stack exchange,提问作者amilana
相关产品推荐
相关产品推荐

