Strider
Strider

Reputation: 3759

How to detect tab change from the active tab page

While searching in the Ionic docs to find how to detect tab change, I found that there is the ionTabsDidChange event that is directly linked to the ion-tabs component.

My purpose is slightly different in the way that I need to listen to the tab change from the page/component related to the tab itself, and use some of its data.

For example, if I have a component named TabXPage, I wonder if there is a way to create a method that helps to listen to the tab change, something like this:

@Component({
  selector: 'app-tabx',
  templateUrl: './tabx.page.html',
  styleUrls: ['./tabx.page.scss'],
})
export class TabXPage implements OnInit {

    //...

    onTabChange() {
        // Execute tab change actions using some data that EXISTS IN TabXPage
    }

}

I looked upon Angular lifecycle hooks, but I did not find any applicable event since the page is preserved in the same state while navigating through the Ionic tabs.

Upvotes: 3

Views: 8337

Answers (2)

Dinesh Gurjar
Dinesh Gurjar

Reputation: 528

in ionic 3 i achieved by using ionSelect() and ionChange() method.

<ion-tabs>
  <ion-tab [root]="tab1Root" (ionSelect)="myMethod()"></ion-tab>
  <ion-tab [root]="tab2Root" (ionChange)="myMethod()"></ion-tab>
  <ion-tab [root]="tab3Root"></ion-tab>
</ion-tabs>

Upvotes: 1

Strider
Strider

Reputation: 3759

I found a solution using Ionic lifecycle hooks, I am not sure if it's the best regarding the subject but it's working for my case.

I used simply the ionViewDidLeave page event:

@Component({
  selector: 'app-tabx',
  templateUrl: './tabx.page.html',
  styleUrls: ['./tabx.page.scss'],
})
export class TabXPage implements OnInit {
    //...

    ionViewDidLeave() {
        console.log("TabX is exited")
    }
}

Upvotes: 4

Related Questions