Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

angular - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...