4

I'm using NgbModal from @ng-bootstrap to open modal windows from an Angular 6 application. In one of these modals, I'd like a button click to close the modal and activate a function in the parent/launching component. How can I do that?

I know that with ordinary child and parent components you can emit an event which is caught by the parent component (see this solution here). Is there something analogous I can do with my modal setup? If not, what's the best approach here?

Current code in the parent (simplified):

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;
  }
}
workerjoe
  • 2,421
  • 1
  • 26
  • 49

1 Answers1

7

The close button of the modal can call the NgbActiveModal.close method, with the modal result value as the parameter:

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>

In the parent component, you handle the NgbModalRef.result promise with the appropriate callbacks. The result value can be retrieved in the "success" callback, in which you can call any method of the parent component:

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

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • Don't worry, I won't forget. I think the best policy is to wait a day or two to see what other solutions might be presented. – workerjoe Nov 01 '18 at 23:59