Set no tab as default active tab on mat tab

User3250 picture User3250 · Dec 17, 2018 · Viewed 9.8k times · Source

I have search functionality implemented using mat-tab, I need no tab selected on initial load. Tab should get active only when user clicks on specific tab.

Currently, first tab is active on load. I have tried setting selectedIndex="null" but didn't work. Also, I need reset the selected tab on a button click.

Search using mat tab

Answer

Commercial Suicide picture Commercial Suicide · Dec 17, 2018

There is no predefined option in the current API version to deselect all tabs because it's implied that at least one tab should be active. But there is a small workaround (and it seems quite good IMHO): we can add one more auxiliary tab at index 0, leave it empty (without any content) and hide it with display: none. This way you have additional invisible tab, and you still have an option to navigate to this tab, which looks pretty close to deselecting all the tabs.

You can achieve it via just a few rows of HTML / CSS.

HTML:

<button (click)="tabs.selectedIndex = 0">RESET</button>
<mat-tab-group #tabs>
  <mat-tab></mat-tab> <!-- ADDITIONAL TAB -->
  <mat-tab label="First">
    <p>Content 1</p>
  </mat-tab>
  <mat-tab label="Second">
    <p>Content 2</p>
  </mat-tab>
  <mat-tab label="Third">
    <p>Content 3</p>
  </mat-tab>
</mat-tab-group>

CSS:

::ng-deep .mat-tab-labels > .mat-tab-label:first-child {
  display: none;
}

And here is a working STACKBLITZ, you can see it in action.