Mat Stepper打开弹窗时如何禁用document级HostListener回车事件监听
解决方案
你只需要新增一个弹窗开启状态标记,在全局回车监听逻辑中增加状态校验即可,修改步骤如下:
- 首先在组件类中新增状态变量
// 标记当前是否有弹窗处于打开状态 private isDialogOpen = false;
- 修改弹窗打开方法,同步更新状态
open(EducationalDialogNo) { // SSC/CBSC dialogs validation commented as ssc not required if (EducationalDialogNo == 1) { console.log("EducationalDialogNo == 1"); // 弹窗打开时标记状态为true this.isDialogOpen = true; this.dialogService.open(FirstDialogComponent).onClose.subscribe((data: any) => { // 弹窗关闭时重置状态为false this.isDialogOpen = false; if (data !== undefined) { this.cbse.university = data.sscUniversity; this.cbse.school_name = data.sscCollege; this.cbse.result_date = data.sscResultDate; this.cbse.school_marks = data.sscMarks; } }, err => { // 弹窗异常关闭时也要重置状态 this.isDialogOpen = false; console.error(err) }); } else if (EducationalDialogNo == 2) { // 其他弹窗逻辑同样要同步更新isDialogOpen状态 } }
- 修改全局回车监听方法,增加状态判断
@HostListener('document:keydown', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { // 有弹窗打开时直接终止后续步进逻辑 if (this.isDialogOpen) return; if (event.key == 'Enter') { if (this.selectedStepper == '0') { if (this.firstForm.valid) { console.log('Stepper 1', this.fifthForm.valid) this.onFirstSubmit() this.stepper.next() } else { this.toastrService.danger('Incomplete Form', 'Message') } } else if (this.selectedStepper == '1') { if (this.secondForm.valid) { console.log('Stepper 2', this.secondForm.valid) this.onSecondSubmit(this.country_birth) this.stepper.next() } else { this.toastrService.danger('Incomplete Form', 'Message') } } else if (this.selectedStepper == '2') { if (this.thirdForm.valid) { console.log('Stepper 3', this.thirdForm.valid) this.onThirdSubmit() this.stepper.next() } else { this.toastrService.danger('Incomplete Form', 'Message') } } else if (this.selectedStepper == '3') { if (this.fourthForm.valid) { console.log('Stepper 4', this.fourthForm.valid) this.onFourthSubmit() // this.stepper.next(); } else { this.toastrService.danger('Incomplete Form', 'Message') } } else if (this.selectedStepper == '4') { if (this.fifthForm.valid) { console.log('Stepper 5', this.fifthForm.valid) this.onFifthSubmit() this.stepper.next() } else { this.toastrService.danger('Incomplete Form', 'Message') } } else if (this.selectedStepper == '5') { if (this.profileCompleteness == true) { console.log('Stepper 6') this.quickApply() } else { this.toastrService.danger('Incomplete Form', 'Message') } } } }
如果组件内还有其他弹窗,只要在所有弹窗的打开、关闭逻辑中同步更新isDialogOpen状态即可。
内容的提问来源于stack exchange,提问作者Anuj Todankar
相关产品推荐
相关产品推荐

