Passing Object from Modal in Ionic 4


#1

I have a modal that displays a list of objects for the user to select from. When they select one, I want to pass that object back to the calling page and close the modal.

I can’t find anything on this for Ionic 4. Most questions are about Ionic 2 and reference a View Controller, which I don’t see in Ionic 4.


#2

these are snippets from a complete project that is linked at the end of this post

This code is from the page launching the modal… Click to view full source code
here you present the modal…

  async presentModal() {
    const modal = await this.modalController.create({
      component: AddTaskModalComponent,
      componentProps: {  }
    });

    // this is where you get the data back from the modal
    modal.onDidDismiss().then((d: any) => this.handleModalDismiss(d));

    // show the modal
    return await modal.present();
  }

here is the function to handle the results from the modal

  handleModalDismiss = ({ data }) => {
    if (data.cancelled) {
      // alert that user cancelled
    } else {
      //save the data
      this.doCreateObject(data);
    }

This code is from the modal component… Click to view full source code

when i dismiss the modal with data i send it back

  dismissModal() {
    this.modalController.dismiss({ ...this.task });
  }

when I cancel the modal i set a flag and send data back

  cancelModal() {
    this.modalController.dismiss({ cancelled: true });
  }

#4

Hi,
I have my code like your, but when I do present, aparantly the modal load because I can see in console the result of the modal when load
ngOnInit() {
console.log(this.value);
}

but don show anything.

Checking your project, in the app.module.ts you have this line

import { AddTaskModalComponent } from ‘./add-task-modal/add-task-modal.component’;

but when I try to import it doesnt give me the option of dot . component I have de the option to choose dot module or page like this:

import { AddTaskModalComponent } from ‘./add-task-modal/add-task-modal.module’;
import { AddTaskModalComponent } from ‘./add-task-modal/add-task-modal.page’;

also in your proyect in the folder of the componente you have 4 files only and I have one more that is de .modele.ts
Why? or how you create the modal, because I create with ionic g page modals/NameofModal
and that command creates me 5 files
NameofMolal.module.ts
NameofMolal.page.html
NameofMolal.page.scss
NameofMolal.page.spec.ts
NameofMolal.page.ts

help, please
Thanks