DEV Community

loading...
Cover image for Ionic modals passing and receiving data

Ionic modals passing and receiving data

dailydevtips1 profile image Chris Bongers Originally published at daily-dev-tips.com ・2 min read

Yesterday we made a modal in Ionic, modals are really cool, but generally, we want to pass or receive data from them.

That will be what we'll be making today, a modal that passes, modifies, and returns data.

The end result for today will look something like this:

Ionic modal passing and receiving data

Passing data to an Ionic modal

Let's first start by passing data to our modal. This is as simple as calling the componentProps on our modalController create function.

number: number = 3;

const modal = await this.modalController.create({
  component: DetailPage,
  componentProps: {
    number: this.number
  }
});
Enter fullscreen mode Exit fullscreen mode

Then in the DetailPage we can retrieve these values by defining them inside our component!

export class DetailPage implements OnInit {
  number: number;

  ngOnInit() {
    console.log(this.number);
  }
}
Enter fullscreen mode Exit fullscreen mode

That is how easy it is to pass data to our modal component.

Ionic modal dismiss receive data

Of course, we also want to be able to receive this data back in our main component (tab1.page.ts).

Before we pass the data back, let's add a function that can modify the number for us.

In our detail.page.html we add the following markup:

<ion-item>
  <ion-icon name="remove-circle" (click)="sub()" item-right></ion-icon>
  <ion-input
    type="number"
    min="1"
    class="ion-text-center"
    [value]="number"
    [(ngModel)]="number"
  ></ion-input>
  <ion-icon name="add-circle" (click)="plus()" item-right></ion-icon>
</ion-item>
Enter fullscreen mode Exit fullscreen mode

Now let's add the plus and sub functions in the detail.page.ts file:

plus() {
    this.number++;
}

sub() {
    this.number--;
}
Enter fullscreen mode Exit fullscreen mode

This will modify our number, but we still need to pass it back to our initial tab1.page. For that, we need to modify the dismiss function.

dismiss() {
    this.modalController.dismiss({
      number: this.number,
    });
}
Enter fullscreen mode Exit fullscreen mode

This will send the number as the variable number.

In our tab1.page.ts we can receive this, but adding a onDidDismiss callback in the presentModal function:

modal.onDidDismiss().then(data => {
  this.number = data.data.number;
});
Enter fullscreen mode Exit fullscreen mode

This will receive the data and update the number.
Then the next time we will open the modal, the new number will reflect.

And there you have it, passing and receiving data in Ionic Modals.

You can find today's code on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Discussion (0)

pic
Editor guide