How to load into specific tab after refresh using angular material tabs?

60 Views Asked by At

I need to be able to load to specific tab after navigating away and back my tabs component or refreshing the page.

I am being able to store the last current tab in local storage

<mat-tab-group #tabGroup (selectedTabChange)="tabChanged($event)">
    <mat-tab label="Overview">1</mat-tab>
    <mat-tab label="Overview">2</mat-tab>
    <mat-tab label="Overview">3</mat-tab>
    <mat-tab label="Overview">4</mat-tab>
</mat-tab-group>
tabChanged(tabChangeEvent: MatTabChangeEvent): void {
  localStorage.removeItem('lastTab');
  this.theIndex = tabChangeEvent.index;
  localStorage.setItem('lastTab', this.theIndex);
}

now when coming back to the page or refresh I need to reload the page to that tab index saved in local storage, how to do that?

1

There are 1 best solutions below

0
On BEST ANSWER

MatTabsGroup has a input called selectedIndex: https://material.angular.io/components/tabs/overview

The active tab may be set using the selectedIndex input or when the user selects one of the tab labels in the header.

So you can use that in your template:

<mat-tab-group [selectedIndex]="selectedIndex" (selectedTabChange)="tabChanged($event)">
  <mat-tab label="Overview">1</mat-tab>
  <mat-tab label="Overview">2</mat-tab>
  <mat-tab label="Overview">3</mat-tab>
  <mat-tab label="Overview">4</mat-tab>
</mat-tab-group>

And in ts, when you first load your component, get the index you saved in localStorage in OnInit:

ngOnInit(): void {
    const savedTabIndex = localStorage.getItem('lastTab');
    this.selectedIndex= savedTabIndex;
  }