【问题标题】:(How) can I call a parent component function from an NgbModal modal?(如何)我可以从 NgbModal 模态调用父组件函数吗?
【发布时间】:2019-04-05 20:37:49
【问题描述】:

我正在使用NgbModal from @ng-bootstrap 从 Angular 6 应用程序打开模式窗口。在其中一个模式中,我想要单击按钮以关闭模式并激活父/启动组件中的功能。我该怎么做?

我知道对于普通的子组件和父组件,您可以发出一个被父组件捕获的事件(请参阅this solution here)。我可以用我的模态设置做一些类似的事情吗?如果没有,这里最好的方法是什么?

父级中的当前代码(简化):

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from "...";
@Component ( {...} )
export class ParentComponent {
  ...
  constructor(private modalService: NgbModal) {}
  ...
  showModal(i:InputObject) {
    const modalRef = this.modalService.open(ModalCompoenent);
    modalRef.componentInstance.i = i;
  }
}

【问题讨论】:

    标签: angular bootstrap-modal parent-child


    【解决方案1】:

    模态的关闭按钮可以调用NgbActiveModal.close方法,以模态结果值作为参数:

    import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap";
    
    export class ModalComponent {
      constructor(public activeModal: NgbActiveModal) { }
    }
    
    <button type="button" (click)="activeModal.close('This is my answer')">Close</button>
    

    在父组件中,您使用适当的回调处理 NgbModalRef.result 承诺。可以在“成功”回调中获取结果值,在该回调中可以调用父组件的任意方法:

    const modalRef = this.modalService.open(ModalComponent);
    ...
    modalRef.result.then(
      (data: any) => {
        this.processData(data);
      },
      (reason: any) => { });
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

    • 别担心,我不会忘记的。我认为最好的策略是等待一两天,看看可能会提出什么其他解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2014-01-31
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多