I'm pretty new to Angular, and I want my code to remember which tab I was on even after I refresh the page or go to another page and then come back. So if I was on tab2 and refresh the browser, I want the page to load tab2 again and not go back to the tab1 as is default with angular material tabs. How would I accomplish this? Thanks!
I'm working with a mat-tab-group that looks something like the following:
<mat-tab-group>
<mat-tab label="Table1">
...
</mat-tab>
<mat-tab label="Table2">
...
</mat-tab>
<mat-tab label="Table3">
...
</mat-tab>
</mat-tab-group>
The "..." is just the table attributes.
The only way to store information client-side that persists after the page is destroyed is with local storage. You could store the info in the browser like so:
handleMatTabChange(event: MatTabChangeEvent) {
localStorage.setItem('userTabLocation', event.index);
}
...with that event being bound to the MatTabGroup
'sselectedIndexChange
event. Then, on page load, get the info from local storage and set the tab:
ngAfterViewInit() {
let index = localStorage.getItem('userTabLocation') || 0; // get stored number or zero if there is nothing stored
this.tabGroup.selectedIndex = index; // with tabGroup being the MatTabGroup accessed through ViewChild
}
I think the better solution would be to tie the current tab to the Router
, and have each tab be in its own route. This will mean that the tabs themselves act like their own pages, and will act as you'd expect via normal browser interaction (refreshing, back, forward, etc.), and you can hyperlink to a specific tab.
Doing this is pretty straightforward. You just use a <mat-tab-nav-bar>
and <mat-tab-link>
instead of groups and tabs. The documentation for this functionality is on the API site here.
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