如何在ngx-bootstrap模态框子组件与父组件间传递数据并捕获事件?
ngx-bootstrap模态框父子组件数据传递与事件捕获解决方案
数据传递(@Input属性赋值)
ngx-bootstrap提供两种方式给模态框子组件传递@Input数据:
方式一:通过initialState传递(官方推荐)
调用show方法时,将@Input属性放入配置的initialState对象中,子组件会自动接收该值:
const modalRef = this.modalServiceNew.show(ListComponent, { class: "model", ...this.modOpt, initialState: { openFrom: "form name" // 对应子组件的@Input() openFrom } });
方式二:直接赋值组件实例
如果习惯ng-bootstrap的写法,也可以在模态框实例创建后,直接给componentInstance赋值:
const modalRef = this.modalServiceNew.show(ListComponent, { class: "model", ...this.modOpt }); modalRef.componentInstance.openFrom = "form name";
事件捕获(@Output订阅)
ngx-bootstrap的ModalRef同样可以通过componentInstance获取子组件实例,进而订阅@Output事件,注意以下细节:
- 确保子组件正确触发事件:子组件中必须调用
EventEmitter的emit方法抛出数据,例如:
// 子组件ListComponent中 this.selecteduse.emit(需要传递的数据);
- 父组件正确订阅事件:
const modalRef = this.modalServiceNew.show(ListComponent, { class: "model", ...this.modOpt, initialState: { openFrom: "form name" } }); // 订阅子组件的selecteduse事件 const eventSubscription = modalRef.componentInstance.selecteduse.subscribe((eventData) => { this.func1(); // 执行父组件逻辑,注意this的指向,避免拼写错误 }); // 模态框关闭时取消订阅,防止内存泄漏 modalRef.onHidden.subscribe(() => { eventSubscription.unsubscribe(); });
常见问题排查
- 确认子组件已正确导入
Output和EventEmitter:import { Input, Output, EventEmitter } from '@angular/core'; - 检查父组件的
modalServiceNew是ngx-bootstrap的BsModalService(导入路径:import { BsModalService } from 'ngx-bootstrap/modal';) - 验证子组件确实触发了
selecteduse.emit()方法 - 检查拼写错误(如代码中的
thid应为this)
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

