[Ionic-v4] Modal Parameters

Hey Guys,

i updated my app to Ionic 4 and noticed, that there is no documented way to open a new modal-dialog with some sort of parameters. The only parameters, which i can use are the ones at the dismiss()-call.

The ModalController allows to use a property “componentProps”, when creating a new modal. But i can’t access the properties in my modal component itself.

Is this a missing piece in Ionic 4 or just not documented?

Thanks!
Kind regards
Patrick

2 Likes

Did you try NavParams in your modal to get the params?

https://forum.ionicframework.com/t/ionic-4-get-data-in-modal-passed-with-componentprops/

As far I understand it works like following

To pass parameters to the modal, use componentProps

const modal: HTMLIonModalElement = this.modalController.create({
   component: MyModal,
   componentProps: {
      something: 'value',
      other: {couldAlsoBeAnObject: true}
   }
});

To get the values in your modal

  const something: string = this.navParams.get('something');

To close the modal and pass a value back

 this.modalController.dismiss(true);

or

 this.modalController.dismiss({couldAlsoBeAnObject: true});

Finally to get the dismissed value back

 modal.onDidDismiss((detail: OverlayEventDetail) => {
     console.log(detail ? detail.data : null); // The value or object is detail.data
 });
5 Likes

Thanks! That worked, i didn’t know, that NavParams exists in v4, as the complete navigation-pattern was implemented with Angular Router.

Agree with you, not that obvious. Cool if it worked out

Are you sure this works, and that you’re using Ionic v4?

I ask because NavParams are no longer supported in Ionic v4 - you will get a static injector error.

1 Like

you don’t need to use the @Input annotation and the data still comes through as properties.

i just went through this issue… the documentation is still a work in progress

1 Like

I stand corrected! It looks like both are valid ways to retrieve parameters. (Odd that there’s no documentation page for it, however, or for NavController.) The static injector error I was getting was a red herring - I believe related to issues setting up the owning module.

Note that if you use NavParams, the values will be available in the constructor, versus if you use the @Input attribute, you’ll have to wait for ngAfterViewInit().

Now to get the dismissed value back is:

modal.onDidDismiss().then( (detail) => console.log(detail.data))
                    .catch( (err) => console.log(err.message);

The value or object is detail.data

Now the function “onDidDismiss” is a promise

2 Likes

Yep, I even wrote an article about it in the meantime: https://medium.com/@david.dalbusco/how-to-declare-and-use-modals-in-ionic-v4-4d3f42ac30a3

1 Like

Saved my bacon again!
I just subscribed to your medium posts.

Haha I didn’t know the expression “saved my bacon”, love it :rofl:

Nice to hear my little blog post was able to help, really cool. Thx for the nice feedback :slight_smile: