Ngx-bootstrap模态框传递已删除实体ID至其他组件问题
问题分析与解决方案
你遇到的核心问题是:动态创建的ngx-bootstrap模态框组件,无法通过父组件模板中的(postDeleted)绑定接收事件——因为模态框是通过modalService.show()动态生成的,并非在父组件模板里静态声明,模板里的事件绑定根本关联不到这个动态组件。
步骤1:修正子组件的方法名笔误
你的模板中Delete按钮调用的是deletePost(),但组件类里写的是deleteBadge(),先统一方法名:
// 子组件类 @Input() post: any; @Output() postDeleted: EventEmitter<number> = new EventEmitter(); deletePost() { // 与模板中的调用保持一致 this.postService.deletePost(this.post.id) .subscribe({ next: () => { this.bsModalRef.hide(); this.postDeleted.emit(this.post.id); // 直接触发事件,无需额外triggerEvent方法 }, error: err => console.log(err) }) }
步骤2:父组件中订阅动态模态框的事件
动态创建的组件需要通过代码直接订阅事件,在openPostModal方法中添加事件监听:
// 父组件类 openPostModal(post: any) { const setup = { class: 'modal-dialog-centered' }; this.postModal = this.modalService.show(ViewPostModalComponent, setup); this.postModal.content.post = post; // 直接订阅子组件的postDeleted事件 this.postModal.content.postDeleted.subscribe((deletedId: number) => { this.onPostDeleted(deletedId); }); }
步骤3:移除父组件模板中无效的事件绑定
父组件循环div上的(postDeleted)绑定完全无效,直接删除:
<!-- 父组件HTML修正后 --> <div *ngFor="let post of posts"> <img [src]="post.photo.url" (click)="openPostModal(post)"> <p>{{post.name}}</p> </div>
步骤4:优化父组件的列表过滤逻辑
无需用JSON.parse(JSON.stringify(...))做深拷贝,直接过滤赋值即可:
// 父组件类 onPostDeleted(id: number) { this.posts = this.posts.filter(post => post.id !== id); }
内容的提问来源于stack exchange,提问作者Alessia
相关产品推荐
相关产品推荐

