MosbahiHaithem
MosbahiHaithem

Reputation: 81

How to show a confirmation message before leaving a Tab in Ionic 3

My ionic 3 application has an ion-tabs with two Tabs. When switching from tab to tab, I need to show a confirmation message ( using AlertController ) to prevent the user from changing the current tab unless he confirms his choice. Is this possible in Ionic ? I've tried showing a confirmation message when tab has been changing. However, I couldn't prevent the new tab from showing up.

Thank you.

Upvotes: 8

Views: 1778

Answers (2)

Timothy Chi
Timothy Chi

Reputation: 1

ionViewCanEnter just fire once when switch tab in first time.

You can use two way binding for tab root.

<ion-tabs tabsPlacement="top" #myTabs>
    <ion-tab (ionSelect)="SwitchTab1()" tabIcon="pricetag" [(root)]="tab1" tabsHideOnSubPages="true"></ion-tab>
    <ion-tab (ionSelect)="SwitchTab2()" tabIcon="attach" [(root)]="tab2" tabsHideOnSubPages="true"></ion-tab>
</ion-tabs>

The example in plunker : https://plnkr.co/edit/FaoZTGZ9VDc8CSq4N9nL?p=preview

  SwitchTab2(){
    if (this.tab2 == null)
      this.Confirm('Are Sure For Switch To Tab 2 ?',() => {
        this.tab2 = Tab2;
        this.tab1 = null;
        setTimeout(() => this.tabRef.select(1));
      })
  }

  Confirm(Message, Action){
    this.alertCtrl.create({
        title: Message,
        buttons: [
          { text: 'Cancel' },
          {
            text: 'Sure',
            handler: Action
          }
        ]
      }).present();
  }

Upvotes: 0

David
David

Reputation: 7507

You can realize such things using Nav guards. You can find them in the ionic-docs for the NavController.

The implementation may look something like this:

ionViewCanEnter(): Promise<any> {
  return new Promise((resolve, reject) => {
    let alert = this.alertCtrl.create({
      title: 'Alert',
      message: 'Please confirm ...',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            reject();
          },
        },
        {
          text: 'Confirm',
          handler: () => {
            resolve();
          },
        },
      ],
    });
    alert.present();
  });
}

Use ionViewCanEnter() as ionViewCanLeave() does currently not work (at least when working with tabs).

Upvotes: 4

Related Questions