简体   繁体   中英

Dismiss ngb-modal outside modal controller

I've created a component with the content of a modal that I want to display on other multiple components.

modal.component.html:

<div class="modal-header">
  <h4 class="modal-title"></h4>
  <button type="button" class="close" aria-label="Close" (click)="dismissModal()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">...</div>

modal.component.js:

export class ModalComponent implements OnInit {
  constructor(
    private modal: NgbActiveModal
  ) { }

  dismissModal() {
    this.modal.dismiss();
  }
}

And I'm calling this content in other parts of my site, such us:

header.component.html:

<button (click)="openModal(myModal)">
    Open Modal
</button>

<ng-template #myModal let-modal>
  <app-modal-content></app-modal-content>
</ng-template>

header.component.ts:

openModal(content: string) {
  this.modalRef = this.modalService.openModal(content, { centered: true });
}

The modal shows up correctly, but when I try to dismiss the modal by pressing X it does not work, because the modal reference is in the header component. How could I dismiss the modal if I'm opening it from other component?

The modal.component.ts file should inject the NgbActiveModal service in order to close the modal.

In the modal.component.ts file constructor:-

import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';

export class ModalComponent {
  constructor(public modal: NgbActiveModal) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM