ngx-bootstrap:子组件关闭BsModal弹窗失败问题求助
解决子组件关闭BsModal弹窗的问题
看起来你遇到的问题主要是组件间通信的细节错误,我帮你梳理两种可行的解决方案:
方案一:修正模板变量大小写,传递BsModalRef实例
你第一种方法报错的核心原因是模板变量大小写不匹配:父组件里弹窗的模板变量是#lgModal2(驼峰式,大写M),但你传给子组件时写的是lgmodal2(小写m),而JS/TS是大小写敏感的,导致子组件的modalId接收到的是undefined,自然调用hide()会报错。
修正后的代码:
父组件HTML
<div bsModal #lgModal2="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">Edit Product</h4> <button type="button" class="close pull-right" (click)="lgModal2.hide()" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- 修正模板变量为lgModal2,和弹窗的#lgModal2一致 --> <app-edit-product [productId]="prodId" [modalId]="lgModal2" #child ></app-edit-product> </div> </div> </div> </div>
子组件TS
import { BsModalRef } from 'ngx-bootstrap'; import { Input, OnInit } from '@angular/core'; export class EditProductComponent implements OnInit { // 给modalId加可选标记,并用可选链避免undefined报错 @Input() modalId?: BsModalRef; somefunction(){ // 使用可选链操作符?.,确保modalId存在时才调用hide() this.modalId?.hide(); } }
方案二:使用@Output事件发射器(更推荐,低耦合)
这种方式不需要传递模态框实例,通过事件通知父组件关闭弹窗,符合Angular单向数据流的设计原则,组件耦合度更低。
修正后的代码:
子组件TS
import { Output, EventEmitter, OnInit } from '@angular/core'; export class EditProductComponent implements OnInit { // 定义事件发射器,不需要传递额外参数 @Output() closeModal = new EventEmitter<void>(); somefunction(){ // 触发关闭事件 this.closeModal.emit(); } }
父组件HTML
<div bsModal #lgModal2="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">Edit Product</h4> <button type="button" class="close pull-right" (click)="lgModal2.hide()" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- 监听子组件的closeModal事件,调用弹窗的hide()方法 --> <app-edit-product [productId]="prodId" (closeModal)="lgModal2.hide()" #child ></app-edit-product> </div> </div> </div> </div>
两种方案都能解决你的问题,个人更推荐方案二,因为它让子组件不需要依赖BsModalRef的具体实现,更利于组件复用和维护。
内容的提问来源于stack exchange,提问作者phpdroid
相关产品推荐
相关产品推荐

