Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task.

@Component({
})
export class MyComponent implements OnInit { 
  openModal() {
   const modal = await this.modalCtrl.create({
      component: MyModalComponent,
   });
   await modal.present();
  }
}

@Component({
})
export class MyModalComponent implements OnInit { 
  fetchData() {
    this.fetchData().subscribe((response) => {
       // carry out necessary operations

       // Dismiss the modal functionality here
    })
  }
}

Answer №1

To begin, you should develop a generic service that wraps the modal functionality and also maintains the state of which modal is returning what data (especially if multiple modals are opened simultaneously).

async showModal(modalPage, fullscreen: boolean, componentProps?) {
let resolveFunction: (res: any) => void;
const promise = new Promise<any>(resolve => {
  resolveFunction = resolve;
});
const modal = await this.modalCtrl.create({
  component: modalPage,
  cssClass: fullscreen ? 'full-screen-modal' : 'half-screen-modal',
  componentProps
});

modal.onDidDismiss().then(res => {
  resolveFunction(res);
});
await modal.present();
return promise;

}

Next, structure your modal page like so:

import { Component, OnInit } from '@angular/core';
import { DisplayService } from 'src/app/services/display/display.service';

@Component({
  selector: 'app-rating',
  templateUrl: './my-modal.page.html',
  styleUrls: ['./my-modal.page.scss'],
})
export class MyModal implements OnInit {

  constructor(private displayService: DisplayService) {}

  ngOnInit() {
  }

  sendValue() {
    // Perform any necessary async tasks here before closing the modal
    this.displayService.closeModal({...returnData}); // Optionally pass return Data here if needed in calling page
  }

}

Finally, your parent page will need to be configured as shown below to display the modals and handle the returned data:

async openModal(){
    await this.displayService.showModal(MyModal, false, null).then( res => {
      // Wait for modal to return data upon closing
      if (res.data.value1){
        const payload = {rating: res.data.value1, remarks: res.data.value2};
        // Make API call 
        this.displayService.showToast(`Thank you`, 'success');
      } else {
        this.router.navigate([`failed-route-view/`]);
      }
    });
  }

Answer №2

An easier method to achieve this is by incorporating the Modal dismiss function directly into your fetchData() function. Here's an illustration:

  fetchData() {
    this.fetchData().subscribe((response) => {
       // perform tasks

       // Dismiss the modal
       this.modalController.dismiss(); 👈🏽
    })
  }

You can also utilize a conditional statement (if) to verify the response data or check if there is currently a Modal open before dismissing it. Keep up the good work!

Answer №3

class ModalComponent {
 fetchData() {
  this.fetchData().subscribe((data) => {
   // perform actions
     this.closeModal()
   })
 }}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Encountered the "Error TS2300: Duplicate identifier 'Account'" issue following the upgrade to Typescript version 2.9.1

Since upgrading to Typescript 2.9.1 (from 2.8), I encountered a compile error: node_modules/typescript/lib/lib.es2017.full.d.ts:33:11 - error TS2300: Duplicate identifier 'Account'. This issue never occurred when I was using typescript 2.7 and ...

What is the reason behind not being able to pass an instance of B to an argument a of type T in Typescript generics when T extends B?

There is a problem with my code: class X<T extends B> [...] // this.p.a :: B | null methodA(a: T):void {[...]} methodB(): void { if(this.p.a){ // :: B this.methodA(this.p.a) // Error My intention was for T to be any type that exten ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Utilize model instance methods in Sails.js for enhanced functionality within views

Is there a way to retain model instance functions when passed to a view? For example, my User model has a method called fullName which combines first name, last name, and prefix. In the controller: User.find().done(function(err,users){ res.view({ ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

initiate a POST request using fetch(), where the data sent becomes the key of

Encountered an issue with sending a POST fetch request where the JSON String turns into the Object Key on the receiving end, specifically when using the { "Content-Type": "application/x-www-form-urlencoded" } header. I attempted to use CircularJSON to res ...

Combine the promises from multiple Promise.all calls by chaining them together using the array returned from

I've embarked on creating my very own blogging platform using node. The code I currently have in place performs the following tasks: It scans through various folders to read `.md` files, where each folder corresponds to a top-level category. The dat ...

Is there a way to use an Angular expression inside an HTML document to determine if a variable is a boolean type?

I'm working with an element in my HTML where I need to determine the type of a variable, specifically whether it's a boolean or not. <button process-indicator="{{typeof(button.processIndicator) === 'boolean' ? 'modalProcess&apo ...

Using RxJS iif with various conditions in combination with Angular 9

I am currently working on creating a service using Angular that will retrieve a specific data set. The format of the object returned by the API looks like this: { status: string, totalResults: number, results: [array of objects] } My goal is to ret ...

Managing errors with promises in Angular 6 using SSH2

Attempting to manage ssh2 error messages using Angular has been a bit challenging for me. I tried implementing a promise to handle it, but unfortunately, it's not working as expected. Being new to this, I apologize if my approach is inadequate, and I& ...

Manipulate the lines in an HTML map and showcase the distinctions between them

I've been searching through various inquiries on this particular subject, but none have provided me with a satisfactory response. I have created a map where I've set up 4 axes using the following code: function axis() { var bounds = ...

An easy way to switch animations using CSS display:none

Dealing with some missing gaps here, hoping to connect the dots and figure this out. I'm attempting to create a functionality where a div slides in and out of view each time a button is clicked. Eventually, I want multiple divs to slide out simultane ...

`Nextjs customizes the position of locales`

Currently implementing i18n translation in my project, the default root appears as follows: https://example.com/en/business/transaction Is it possible to customize the root to appear as: https://example.com/business/en/transacation Thank you. ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

transferring various data from JavaScript page to PHP page

Is it possible to pass multiple values from a service page to a PHP page? I am trying to pass the values 'data', 'albimg' and 'albvideo' to the PHP page, but I keep encountering an error. Please refer to the image below for mo ...

What is the best way to free up memory after receiving responseText in a continuous streaming request?

Utilizing xmlHTTPRequest to fetch data from a continuous motion JPEG data stream involves an interesting trick where responseText can populate data even before the request is completed, since it will never actually finish. However, I have encountered some ...

Script executing single run only

I'm currently working on a side menu that slides open and closed from the left with the press of a button. I have successfully implemented the CSS and HTML code, but I am facing issues with the JavaScript. The functionality works flawlessly at first: ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far: <div id="box" style=&ap ...