Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set no tab as default active tab on mat tab

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

like image 615
User3250 Avatar asked Dec 07 '22 13:12

User3250


1 Answers

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.

like image 188
Commercial Suicide Avatar answered Dec 28 '22 08:12

Commercial Suicide