(如何)我可以从 NgbModal 模态调用父组件函数?
(How) can I call a parent component function from an NgbModal modal?
我正在使用 NgbModal from @ng-bootstrap 从 Angular 6 应用程序打开模态 windows。在这些模式之一中,我想要单击按钮以关闭模式并激活 parent/launching 组件中的功能。我该怎么做?
我知道,对于普通的子组件和父组件,您可以发出由父组件捕获的事件(请参阅 )。我可以用我的模态设置做一些类似的事情吗?如果不是,最好的方法是什么?
父级中的当前代码(简体):
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;
}
}
模态的关闭按钮可以调用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 承诺。结果值可以在"success"回调中获取,回调中可以调用父组件的任意方法:
const modalRef = this.modalService.open(ModalComponent);
...
modalRef.result.then(
(data: any) => {
this.processData(data);
},
(reason: any) => { });
有关演示,请参阅 this stackblitz。
我正在使用 NgbModal from @ng-bootstrap 从 Angular 6 应用程序打开模态 windows。在这些模式之一中,我想要单击按钮以关闭模式并激活 parent/launching 组件中的功能。我该怎么做?
我知道,对于普通的子组件和父组件,您可以发出由父组件捕获的事件(请参阅
父级中的当前代码(简体):
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;
}
}
模态的关闭按钮可以调用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 承诺。结果值可以在"success"回调中获取,回调中可以调用父组件的任意方法:
const modalRef = this.modalService.open(ModalComponent);
...
modalRef.result.then(
(data: any) => {
this.processData(data);
},
(reason: any) => { });
有关演示,请参阅 this stackblitz。