Tabs in the Apex Material Library provide a great user experience while on a page but navigation can introduce issues:
- User navigates to the page with the tabs. The first tab is active.
- User clicks the third tab. The tab contains a list with anchors to navigate to other pages.
- User clicks a link to go to a different page.
- User clicks the back button. The system displays the page with the first tab active.
- User frowns.
The same thing happens when the user reloads the page:
- User navigates to the page with the tabs. The first tab is active.
- User clicks the third tab.
- User reloads the page. The system displays the page with the first tab active.
- User frowns.
The Solution
It is easy to improve the usability of tabs using Apex Designer. The design pattern uses a tabIndex query parameter in the page URL to retain the current tab.
Add a tabIndex Property
First add a tabIndex property of type number:
Bind tabIndex to the Tab Group
Next bind tabIndex to the selectedIndex attribute on the Tab Group:
Add a setTab Method
Next add a setTab method to your page with this implementation:
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
tabIndex: this.tabIndex
},
queryParamsHandling: 'merge',
replaceUrl: true
});
Normally router.navigate is used to go to a different page. In this case, the empty array along with the "relativeTo" option keeps the user on the same page. The "queryParams" option sets the tabIndex query parameter. The "queryParamsHandling" option merges the tabIndex parameter with any others that are already there. Finally the "replaceUrl" option tells Angular not to add this change to the browser history (more on that later).
Trigger setTab on tabIndex Change
Next trigger setTab when tabIndex changes:
Add a getTab Method
Finally, add a getTab method set to be called automatically on load with this implementation:
this.subscription = this.route.queryParams.subscribe((params) => {
this.tabIndex = params.tabIndex;
});
The code subscribes to changes in the queryParameters and updates tabIndex appropriately. Since the Tab Group is linked to tabIndex, it will automatically change the current to the tabIndex value from the queryParameter. Be sure to clean up your subscriptions as described in Cleaning Up Subscriptions.
Changing Tabs with the Back Button
If you want the back button to move to the previous tab, just remove the "replaceUrl" option in the setTab method implementation:
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
tabIndex: this.tabIndex
},
queryParamsHandling: 'merge'
});