Ionic 2 tabs disappear when navigating from side menu

I have a tabs application with a side menu, when I click an item from the side menu, I want it to change the root view on the first tab. NOT set the root view entirely, because then the tabs disappear.

I have this as the click method on the side menu items:

openPage(page) {
    this.nav.setRoot(page.component);
}

The problem is that gets rid of the tabs, I want the sidebar to hide and change the root of the first tab (or tab i decide to select) as that page.component variable.

I’ve tried a bunch of different ways with this.nav.parent and such, but can not get it to work.

Also it’s weird that if I search this error, the solution is the code above, but for me does not work as they say.

Any help is appreciated.

2 Likes

So you’ll want to navigate to the tabs page and send a parameter of the tab that you want to navigate to.

openPage(page, index) {
    this.nav.setRoot(page.component, {tabIndex: index});
}

and then use that in the tabs page constructor:

mySelectedIndex: number;

constructor(public navParams: NavParams) {
    this.mySelectedIndex = navParams.data.tabIndex || 0;
}

lastly use mySelectedIndex in the html for the tabs:

<ion-tabs [selectedIndex]="mySelectedIndex">
    // Tabs here
</ion-tabs>

Hope this helps. You can also take a look at the Conference App for a great example on doing this.

Yes this is good, but I also want to set the root of the tab to a different component as well.

For example, the first tab shows a list of data, and the options in the sidebar load different lists of data for the first tab, but those lists are all different components. Possible?

I see. Without using a service you might try something like:

openPage(page, index) {
    this.nav.setRoot(tabPage, {tab1Component: page.component, tabIndex: index});
}

and then in the tabs page:

mySelectedIndex: number;
tab1Root: any;

constructor(public navParams: NavParams) {
    this.mySelectedIndex = navParams.data.tabIndex || 0;
    this.tab1Root = navParams.data.tab1Component || defaultPage;
}

Don’t know if you can change the root in that way so what you might need to do is have a service to hold what the root component for the first tab is. The side menu controller would then call something like:

openPage(page, index) {
    this.myService.setTab1Root(page);
    this.nav.setRoot(page.component, {tabIndex: index});
}

Then in the tab controller you need to get the component for tab 1 from myService with something like:

ionViewWillLoad() {
    tab1Root = this.myService.getTab1Root();
}

I don’t think I know enough yet to comprehend all of what you said, so i’m going to do some reading. Thanks for the help!

I’ll report back and let you know.

Take a look at this pluker demo I made:

Very rudmentary and not using a side nav but it does demo opening a tabs page using an given page as the root page for the first tab. Shows that it is possible just needs to be adapted to your use case.