Using Ionic 4, and tabs. Suppose that we have Tab1 / Tab2 / Tab3 with the default app generated by Ionic. I want to use the hardware back button, to exit app if I'm in Tab1, but I need to go back on Tab1 if I am in an other tab.
Currently my code works, but : For example if I am in Tab2 then I use the hardware back button, then the routing works, I am redirected to Tab1, but Tab2 icon remain selected. (Tab1 icon is also selected but it's normal since I have been routed to this tab)
tabs.html :
<ion-tab-bar slot="bottom">
<ion-tab-button tab="tab1">
<ion-icon name="flash"></ion-icon>
<ion-label>Tab One</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab2">
<ion-icon name="apps"></ion-icon>
<ion-label>Tab Two</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab3">
<ion-icon name="send"></ion-icon>
<ion-label>Tab Three</ion-label>
</ion-tab-button>
</ion-tab-bar>
Tab1.ts :
ionViewWillEnter() {
this.subscription = this.platform.backButton.subscribe(() => {
navigator['app'].exitApp();
});
}
Tab2.ts :
ionViewWillEnter() {
this.subscription = this.platform.backButton.subscribe(() => {
this.navCtrl.navigateRoot('/tabs');
});
}
In Tab2.ts navcontroller route well to /tabs (which mean, in the routing rules, go to tab1.) Of course, in both case, subscription is unsubscribe in an ionViewDidLeave lifecycle hook.
But anyway, how to make the tab2 icon unselected when hardware back button is used to navigate to tab1 ? It's like if the tabbar was notified that tab1 has been selected (because Tab1 icon is automatically selected), but tabbar wasn't notified to unselect Tab2 icon. That mean I have two icons selected in tabbar.
Thanks
After tracing what happens on actual devices, it appears that some phones (observed on Samsung S20+, 10+ and not on Motorola G9 for instance) set the :hover element state to the tab button when you tap it. Using the OS back navigation doesn't interact with the app UI and leaves the tab in that hovered state.
Ionic defines this CSS causing the tab to appear active on hover, which is fine if you are actually hovering it with your mouse:
@media (any-hover: hover) a:hover {
color: var(--color-selected);
}
To fight that, add this to your CSS:
ion-tab-button:not(.tab-selected)::part(native):hover {
color: var(--color);
}
Explanation: we're targeting the <a part="native"> tag inside tab buttons that are not selected but are hovered and restore their color to current text color.
If you want to keep the hover effect on desktop, you can combine the above rule with :not(.plt-desktop).
As to why a phone may have a hover effect without having a mouse, the question remains open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With