You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular12中如何从NgbModal组件向外触发EventEmitter自定义事件?

问题根因

你定义的clickEvnt是ModalContent内部组件的输出事件,而你在父组件中是给外层的confirmation-modal组件绑定的事件监听,后者本身没有对外暴露clickEvnt输出事件,也没有做内部事件的透传,因此父组件无法收到事件。

修复步骤

第一步:给ConfirmationModalComponent添加输出事件与透传逻辑

修改MODAL.COMPONENT.TS里的ConfirmationModalComponent代码:

import { Component, OnInit, Output, EventEmitter } from '@angular/core'; // 确保引入Output和EventEmitter
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

// ... 上方ModalContent代码保持不变

@Component({
  selector: 'confirmation-modal',
  templateUrl: './confirmation-modal.component.html'
})
export class ConfirmationModalComponent implements OnInit {
  // 新增对外暴露的输出事件
  @Output() clickEvnt = new EventEmitter();

  constructor(private modalService: NgbModal) {}

  ngOnInit(): void {
  }
  open() {
    const modalRef = this.modalService.open(ModalContent);
    modalRef.componentInstance.title = 'Delete';
    modalRef.componentInstance.content = 'Are you sure you want to delete this task?';
    modalRef.componentInstance.primaryButtonText="Yes";
    modalRef.componentInstance.secondaryButtonText="No";    

    // 新增:订阅内部ModalContent的clickEvnt事件,透传给外层父组件
    modalRef.componentInstance.clickEvnt.subscribe(() => {
      this.clickEvnt.emit();
      // 触发事件后关闭模态框,可按需保留
      modalRef.close();
    });
  }
}

可选优化方案

你也可以直接通过NgbModal自带的关闭回调传递数据,省去自定义内部Output的步骤:

  1. 修改ModalContent的remove方法,直接通过activeModal关闭时传标识:
remove() {
  this.activeModal.close('confirm');
}
  1. 在ConfirmationModalComponent中订阅模态框关闭结果:
open() {
  const modalRef = this.modalService.open(ModalContent);
  // ... 其他赋值逻辑不变
  modalRef.afterClosed().subscribe(result => {
    if(result === 'confirm') {
      this.clickEvnt.emit();
    }
  })
}

两种方案都可以正常触发父组件绑定的onDelete方法。


内容的提问来源于stack exchange,提问作者LOTUSMS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:15:01