Angular NgbModal, how to correctly close a modal window?

17.4k views Asked by At

I am working on an Angular application using NgbModal to handle modal. I have some doubts about how properly close a modal implemented with this component (untill now I always used PrimeNg instead ng-bootstrap).

Basically I have done in this way (and it seems to works fine): into my TypeScript code I have something like this:

async post(): Promise<void> {
    this.submitted.next(true);
    try {
      await this.setAddress();
      this.modalService.dismissAll();
    } catch (e) {
      console.error('Storage upload error', e);
      this.submitted.next(false);
    }
}

Basically this method is called when a post is submitted. The setAddress() method save on the database (calling another service method) the form values. Then the modal was closed. It seems to works fine but I have the following doubt:

As you can see in order to close my modal I am using this dismissAll() method. Checking on the documentation: https://ng-bootstrap.github.io/#/components/modal/api

It also indicates a close() method that I can not use on my code. Trying:

this.modalService.close();

the IDE says to me:

Property 'close' does not exist on type 'NgbModal'.ts(2339)

Why in the official documentation I have this method but not in my code? The first used method (dismissAll()) is it correct? It is working but I have some doubts related to this "All" into the method name. Why "All"? it let me think that it is closing all the modals and not only a single one (in my use case in my page there is only a single modal so it is indifferent but I am not sure that I am implementing the correct logic to close my modal)

3

There are 3 answers

0
penguintheorem On BEST ANSWER

you're probably looking for the close method of this class. You need to inject the NgbActiveModal into your component instead of the NgbModal service.

I use the close method to gracefully close the modal. You could use the dismiss method when you want to return an error to the opener and dismissAll when there is more than one active moda instance.

0
Kiran Shinde On

You have to set reference of your opened modal

Like

this.modalReference = this.modalService.open(modalComponent);

And then for closing

this.modalReference.close();
0
Deepika Gupta On

Pass the let-c="close" into the saveChanges() as parameter like below

<button *ngIf="!showloader" type="button" class="btn btn-primary" (click)="saveChanges(c)">

Use it under component method like below and modal will be closed

saveChanges(close) {
  // Additional implementation code here
  // .... & finally close the modal
  close('Close Clicked');
}

Similar question here