简体   繁体   中英

Angular NgbModal, how to correctly close a modal window?

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)

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.

You have to set reference of your opened modal

Like

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

And then for closing

this.modalReference.close();

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