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

Viewed 1473

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.

2 Answers

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();
  }
Related