Search code examples
angularangular-materialmat-tab

Material tabs change to last tab when selectedIndex is higher than the actual number of tabs


For example, I have 2 tabs in my mat-tab-group:

<mat-tab-group>
  <mat-tab>
  </mat-tab>
  <mat-tab>
  </mat-tab>
</mat-tab-group>

Let's say the first tab is chosen (index 0), when I change selectedIndex to 2 (which should switch to tab 3 but it doesn't exist) the second tab is chosen. I want the first tab to remain selected because the index was out of range. How can I do that? (For a generic case: n number of tabs, one of them selected (not necessarily the first or last one, and selectedIndex>n)


Solution

  • Try this:

    In TS:

    let index = this.Activeroute.snapshot.queryParams['index'];
    
    if(selectedIndex > n)
    {
       this.selectedIndex = 0;
    }
    else
    {
       this.selectedIndex = index;
    }