Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set active tab when navigating from one tab to another by button click

Tags:

ionic2

ionic3

I have been struggling with this for a while now. I'm trying to navigate to one tab (let's say Home) to another (let's say About). I'm able to navigate that either the page get's added to nav stack, but then it's not changing active tab. That, or then we use select to set the active tab, which means that I lose the navigation stack. Here's the latter option code:

export class HomePage implements OnInit {

  tab: Tabs;

  constructor(public navCtrl: NavController) {
    this.tab = this.navCtrl.parent;
  } 

  navigate() {
    this.tab.select(1);
  }

But this means that as mentioned, I lose the nav stack and can't use the back button that would show if I use push. That brings us to the other option, when I use .push():

this.navCtrl.push(About)

The active tab won't change, but still shows Home as the active tab, even though we are successfully navigated to About tab.

So what I wish for, is to have both the 'Back' button and the active tab (About) selected when I'm clicking the button to go to About from Home. Here's a demo with the push option, as you can see the active tab does not change: https://plnkr.co/edit/6KIL8mxfTMCsvACpiD1K?p=preview

PS. I looked at this question, but it wasn't useful to me: Changing tabs dynamically in Ionic 2

I'm using Ionic 3

like image 592
DRNR Avatar asked Dec 04 '25 07:12

DRNR


1 Answers

I don't think this is how the tabs component is intended to work. With tabbed navigation you kind of have n navigation stacks (where n is the number of different tabs you have) which means if you .push() a new page on the nav-stack you push it on the stack of the currently selected tab.

Switching to another tab kind of is the same as starting with a new root, you start with the initial page ([root]="yourFirstPage") and can then add new pages to this particular nav-stack (and you can pop them off the nav-stack with a back button).

In you particular example you are trying to .push() the About page on the stack of the Home page and expect the NavController to know that you intended to switch to another stack and to push a new page to the new stack.

One solution to your problem could be to always remember the previous tab when you use .select() and display back button manually in the navbar which uses .select(previousTab) on click.

I hope that makes things clearer for you.

like image 58
David Avatar answered Dec 06 '25 06:12

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!