Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being new to Ionic, I am unsure how to accomplish this. I have come across suggestions on Stack Overflow about using *ngIf, but I find it confusing. I've attempted to add code gradually based on the recommendations. Here are the relevant code snippets for your reference. Any assistance would be greatly appreciated.

.html

// Modal 1

<ion-content class="ion-text-left ion-padding">
    <div>
        <ion-text><h2><b>Provide feedback</b></h2></ion-text>
        <h4><p>You are providing feedback on the following appointment:</p></h4>

        <ion-text>Provider name</ion-text>
        <br><ion-label>{{selectedAppointment.providerName}}</ion-label>

        // More form fields and questions...

        <ion-col *ngIf="!feedbackMode">
            <ion-button icon-end expand ="full" shape = "round" size = "large" color="primary" (click)="onSubmitFeedback()">Submit Feedback!</ion-button>
        </ion-col>


    <ion-grid>
       <ion-row>
         // Additional layout and buttons...
       </ion-grid>

    </div>

</ion-content> 

Once the feedback is submitted successfully, Modal2 should display the message "Feedback submitted successfully".

.ts

export class AppointmentSubmitFeedbackComponent implements OnInit {

     feedbackMode: Boolean = false;

    onFeedbackMode(feedbackMode: Boolean) {
      this.feedbackMode = feedbackMode;
    }

     onSubmitFeedback() {
        // Code for submitting feedback and handling response...
        
        this.modalController.dismiss(
          {message: "This is dummy message"},
            'confirm'
           );
      }

Answer №1

To close Modal 1 and open another modal, utilize the Dismiss Function within your API Response like so:

this.modalCtrl.dismiss({  // This code will dismiss the current modal (Modal 1)
   'dismissed': true
});
this.openThanksModal();  // Opens the Thanks modal after dismissing Modal 1

Answer №2

When using a modal to call another model on Ionic, there are some caveats to keep in mind. The first modal will be destroyed before showing the second one, presenting 3 alternatives:

  1. To control the second modal using logic on the parent page of the modals.
  2. To change the layout of the current modal with *ngIf.
  3. To use an Alert to display the "thanks" message.

From a UX perspective, it is preferable to go with option #3 as it is better to show alert messages that are short and direct.


#1. Showing Another Modal When the First One is Dismissed

In your parent page where you call AppointmentSubmitFeedbackComponent:


const modal = await this.modalCtrl.create({ component: AppointmentSubmitFeedbackComponent })

modal.onDidDismiss().then(async (dismissResult) => {
  //This will contain the object returned when the modal dismisses itself
  const returnedData = dismissResult.data 
  
  if(returnedData.success === true) {
    //Show the second modal
    const modal = await this.modalCtrl.create({ component: ThanksModalComponent })
    await modal.present()
  } else {
    //Show error
  }

In your AppointmentSubmitFeedbackComponent:
Remember to declare the modalCtrl in your constructor

onSubmitFeedback() {
  this.postFeedback.caseId = this.selectedAppointment.caseId;
  this.postFeedback.providerCity = this.selectedAppointment.providerCity;
  this.postFeedback.providerCountry = this.selectedAppointment.providerCountry;
  console.log(this.postFeedback);
  let feedbackServ = this.feedbackServ.postFeedback(this.postFeedback);
  feedbackServ.then(response => {
    console.log('response : ', response);
    
    this.modalCtrl.dismiss({ success: true })
  }).catch(error => {
    console.log('errProfile: ', error);

    this.modalCtrl.dismiss({ success: false })
  })
}

#2. Using *ngIf-else

appointment-submit-feedback.component.html

<ion-content *ngIf="!submitted; else thanksContent" class="ion-text-left ion-padding">
  <div>
    <ion-text>
      <h2><b>Provide feedback</b></h2>
    </ion-text>
    <h4>
      <p>You are giving feedback on the
        following appointment:</p>
    </h4>

    <ion-text>Provider name</ion-text>
    <br>
    <ion-label>{{selectedAppointment.providerName}}</ion-label>
    <br>
    <ion-text>Specialty</ion-text>
    <br>
    <ion-label>{{selectedAppointment.specialty}}</ion-label>
    <br>
    <ion-text>Patient name</ion-text>
    <br>
    <ion-label>{{selectedAppointment.patientName}}</ion-label>
    <br>
    <ion-text>Date of appointment</ion-text>
    <br>
    <ion-label>{{selectedAppointment.date | date:'MMM dd,yyyy'}}</ion-label>

    <ion-item></ion-item>
    <br>
    <ion-row>
      <ion-col>
        <ion-text>Please answer the following questions and submit your feedback</ion-text>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <p class="question">Who was your treating physician?</p>
      </ion-col>
    </ion-row>


    ...Rest of the code here...
  
</ion-content>

...Rest of the code...

appointment-submit-feedback.component.ts

submitted = false

closeModal() {
  this.modalCtrl.dismiss()
}

onSubmitFeedback() {
  this.postFeedback.caseId = this.selectedAppointment.caseId;
  this.postFeedback.providerCity = this.selectedAppointment.providerCity;
  this.postFeedback.providerCountry = this.selectedAppointment.providerCountry;
  console.log(this.postFeedback);
  let feedbackServ = this.feedbackServ.postFeedback(this.postFeedback);
  feedbackServ.then(response => {
    console.log('response : ', response);
    this.submitted = true
  }).catch(error => {
    console.log('errProfile: ', error);
    this.submitted = true
  })
}

#3.

appointment-submit-feedback.component.ts

//Declare the alertCtrl in the constructor
constructor( //...
  private alertCtrl: AlertController,
  // ...
)
onSubmitFeedback() {
  this.postFeedback.caseId = this.selectedAppointment.caseId;
  this.postFeedback.providerCity = this.selectedAppointment.providerCity;
  this.postFeedback.providerCountry = this.selectedAppointment.providerCountry;
  console.log(this.postFeedback);
  let feedbackServ = this.feedbackServ.postFeedback(this.postFeedback);
  feedbackServ.then(async (response) => {
    console.log('response : ', response);
    this.showThanksAlert()
  }).catch(error => {
    console.log('errProfile: ', error);
  })
}

showThanksAlert() {
  const alert = await this.alertCtrl.create({
    message: 'Thanks for your submission',
    buttons: [ 
      {
        text: 'Ok',
        handler: () => {
          this.modalCtrl.dismiss()
        }
      }
    ]
  })
  await alert.present()
}

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

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

Clicking does not trigger scrollIntoView to work properly

I'm facing an issue with a button that is supposed to scroll the page down to a specific div when clicked. I implemented a scrollIntoView function in JavaScript and attached it to the button using onClick. Although the onClick event is functioning as ...

Transferring Information from Vue to PHP: What You Need to Know

I need assistance with passing data from Vue to PHP. Currently, I receive a JSON object through a PHP query that looks like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded, ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Resizing webpages for mobile devices results in misaligned rows

I'm currently using Bootstrap on a website and encountering issues with the responsiveness of rows on mobile devices. The desired outcome is for rows to be divided into 4 equal sections per row on larger screens, then scale down to 2 equal sections p ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

Implementing one-to-many data updates in ASP.NET MVC using jQuery dialogs

Imagine this situation: I am working on a view for creating orders. The view includes header information such as the customer's address, delivery mode, and more. Additionally, there is a grid that displays the list of products that the customer has or ...

Issue with React redirect not functioning post transition

A component I created includes a redirection route that triggers after an animation finishes. Here is the code for reference: Menus.jsx class Menus extends Component{ constructor (props) { super(props); this.state = { select: 'esp ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

Flexbox Resizing Notification(?)

Recently, I've been utilizing flexbox in my layout design and it has been a game-changer. However, I am facing an issue that might be linked to my heavy use of AngularJS, particularly the ng-include feature. The specific problem arises when I incorpo ...

Transform form data from square notation to dot notation using jQuery

During my ajax operations, I noticed that the data being sent is in JSON format. However, when checking Chrome tools -> network XHR, I observed that the form parameters are displayed within square brackets. Example: source[title]:xxxxxxxxxxxx source[th ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Executing numerous GET requests with varying parameters in AngularJS

Update: My apologies to those who answered, it turns out that the code was correct, but requests were being intercepted and losing all parameters. I am attempting to send repeated HTTP GET requests to a REST API based on the response, using the solution I ...

Angular | The parameter type 'User[]' is incompatible with the expected parameter type 'Expected<User>' and cannot be assigned

While testing Angular, I encountered this error that has me stumped. The issue seems to be with the user inside the toBe() function. This error is occurring in the file user.service.spec.ts it('should call getUsersById', () => { const user ...

The error message 'ReferenceError: MouseEvent is not defined' indicates that

Recently, I attempted to incorporate ng2-select into a project that relies on angular/universal-starter (TypeScript 2.x) as its foundation. (Interestingly, ng2-select worked perfectly fine when added to an angular-cli generated project.) However, upon ad ...

Disappearing Div Dilemma: The Mystery of the Responsive Design

I am currently facing an issue where two div elements (`.left` and `.right`) are not displayed vertically when the width value is less than 800px. Strangely, the `.left` div disappears when I try to adjust the width. I have shortened the code for clarity. ...

The width of the TD element does not affect the grid

<div id="unique-example" class="k-unique-content"> <table id="unique-grid" style="float: left; position: relative"> <thead> <tr> <th width ="410px"data-field="UniqueFileName">Unique File Name ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...