Search code examples
javascriptangulartypescriptionic2modal-dialog

How to call a callback function from a modal


On load for my home page I ask my user to set a default city. This is one of two places in the app where the default city can be changed therefore I've created a service for it.

In the constructor of the home page I call a function on the service that opens a modal where user can select from list of cities. I do not open the modal directly via home.ts, it's through a function on the service. When that modal closes after catching the city selection , I need a way to change the defaultCity property on the home.ts page.

The documentation here shows how to pass a callback to the create() method on the modal controller, not necessarily how to pass a call back to a function which calls another function which creates the modal. This question deals specifically with Ionic 2 modals. https://ionicframework.com/docs/api/components/modal/ModalController/

Home.ts

    import { Component } from '@angular/core';
    import { LoadingController, ModalController, NavController, PopoverController } from 'ionic-angular';
    import { changeDefaultCity } from '../../services/changeDefaultCity.service';
    
    @Component({
        selector: 'page-home',
        templateUrl: 'home.html',
        providers: [changeDefaultCity] 
    })
    
    export class Home {
    
        defaultCity: string; 
        
            constructor (   public navCtrl: NavController,
                                    public modalCtrl: ModalController,
                                    public loading: LoadingController,
                                    public chngDfCity: changeDefaultCity) {
    
        
    /*if default city isn't selected yet then show city select options on modal*/
    
            if(!this.selectedCity){
    
                    let setDefaultCityFunction = function(dfCity){  
                                                           //CALLBACK I WANT TO USE
    
                                   this.defaultCity = dfCity; 
    
                              };
    
                  this.chngDfCity.presentModal(); //CALL A FUNCTION ON SERVICE WHICH OPENS MODAL
    
            }
    
    
        } // end of constructor
                
    }//END CLASS

myService.ts

import { Injectable } from '@angular/core';
import { ModalController } from 'ionic-angular';
import { SetDefaultCity } from '../pages/set-default-city/set-default-city';


@Injectable()
export class changeDefaultCity {


defaultCity: string; 

    constructor(public modalCtrl: ModalController) {

}//end of constructor


/*Open modal and show the list of city options*/ 

    presentModal() {
    let modal = this.modalCtrl.create(SetDefaultCity);
    modal.present();
  }

  /*on city select, set the selection to defaultCity property*/  

    getDefaultCity(dfCity){

                this.defaultCity = dfCity; 
            
        }

  }//end of class 

setDefaultCity.html //PAGE PASSED TO MODAL

<ion-header>
   //header stuff
</ion-header>


<ion-content padding>


<ion-list [(ngModel)]="defaultCity" (ionChange)="setDefaultCity(defaultCity)" radio-group>
  <ion-list-header>
    
  </ion-list-header>

  <ion-item>
    <ion-label>New York</ion-label>
    <ion-radio value="New York"></ion-radio>
  </ion-item>
  <ion-item>
    <ion-label>Los Angeles</ion-label>
    <ion-radio value="Los Angeles"></ion-radio>
  </ion-item>
  <ion-item>
    <ion-label>San Francisco</ion-label>
    <ion-radio value="San Francisco"></ion-radio>
  </ion-item>
  <ion-item>
    <ion-label>Philadelphia</ion-label>
    <ion-radio value="philadelphia"></ion-radio>
  </ion-item>
 
</ion-list>

</ion-content>

setDefaultCity.ts

/* TS FOR THE PAGE PASSED TO THE MODAL. I USE THIS TS TO PASS THE CITY SELECTION TO THE SERVICE WHICH SHOULD PASS IT BACK TO HOME.TS*/

import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { changeDefaultCity } from '../../services/changeDefaultCity.service';


@Component({
  selector: 'page-set-default-city',
  templateUrl: 'set-default-city.html',
  providers: [changeDefaultCity] 
})
export class SetDefaultCity {

defaultCity: string; 

  constructor(public navCtrl: NavController, public chngDfCity: changeDefaultCity, public viewCtrl: ViewController) {  

 }//END OF CONSTRUCTOR

  ionViewDidLoad() {
    console.log('Hello SetDefaultCityPage Page');

}

   //CALL THIS FUNCTION ON CHANGE WHICH THEN PASSES THE SELECTION TO THE SERVICE.  

  setDefaultCity(defaultCity){

      this.defaultCity = defaultCity; 

      this.chngDfCity.getDefaultCity(this.defaultCity); //SERVICE

    
          this.viewCtrl.dismiss();       

  
  }//end setDefaultCity

}//end class

Solution

  • You'll need to return the city to a function in onDidDismiss() But first take out that service, there's no use to it and you just need to call a modal to get a city. It could be useful if you hade too many cities and want to call a service from a modal to get all the cities.

    So in yout home.ts call the modal

    presentModal() {
      let modal = this.modalCtrl.create(SetDefaultCity);
      modal.onDidDismiss(data =>{
        if(data != null) { // check if null in case user quits the page and dont select a city
          return data;
        } // use and else if you need to treat if the user haven't choose a city
      })
      modal.present();
    }
    

    In your modal you can dismiss passing parameters back, with navController you can't do this, so if someday you need to get call a page to do something and return a data, just use modal instead of the normal navCtrl.push().

    I don't know if you're using and

    setDefaultCity(){
      this.viewCtrl.dismiss(this.defaultCity);       
    }
    
    ionViewWillUnload(){ // or ionViewWillLeave
      this.viewCtrl.dismiss(null); // this way you can treat if a user haven't selected a city and has left the page
    }
    

    Hope this helps :D