15

I have a tab group in Angular. I want that by default the first tab will be selected.
However, when I set the selectedIndex to 0, it doesn't select the first tab, while setting it to 1 or 2 does select the other tabs.

This is my app.component.html:

<mat-toolbar color="primary">
  <span color="white">קשת נחושה</span>
  <span class="spacer"></span>
  <button mat-icon-button>
        <mat-icon class="example-icon">more_vert</mat-icon>
  </button>
</mat-toolbar>
<mat-tab-group mat-stretch-tabs [selectedIndex]="0" (focusChange)="selectedTab($event)">
  <mat-tab>
    <ng-template mat-tab-label>
      <mat-icon>home</mat-icon>
    </ng-template>
  </mat-tab>
  <mat-tab>
    <ng-template mat-tab-label>
      <mat-icon>book</mat-icon>
    </ng-template>
  </mat-tab>
  <mat-tab>
    <ng-template mat-tab-label>
      <mat-icon>message</mat-icon>
    </ng-template>
  </mat-tab>
</mat-tab-group>
<router-outlet></router-outlet>
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
amitairos
  • 2,907
  • 11
  • 50
  • 84

3 Answers3

25

it's a bug but you can use 2 ways data binding, it works

<md-tab-group [(selectedIndex)]="value">
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
  • Another option is to use both `@Input` and `@Output` like this: `` and use the function with the event which is the new tab's index (number), for any further actions. – ntrch May 23 '19 at 09:19
  • Good to see this is still not fixed a year and a half later. – user3640967 Aug 15 '19 at 13:56
2

My tab was selected but the styling did not update. I had to set:

.mat-tab-label-active {
  opacity: 1;
}

I also had to set: encapsulation: ViewEncapsulation.None // inside @Component

alex351
  • 1,826
  • 1
  • 21
  • 32
  • Also answered here: https://stackoverflow.com/questions/48437733/mat-tab-group-doesnt-show-styles-for-default-tab-selected – Spikolynn Mar 12 '21 at 01:03
  • finding the class and apply it as per requirement is very tedious job, that for the quick solution available. – Prasad Shinde Mar 22 '21 at 08:59
1

I encountered this too. This usually happens when you have a custom component for rendering mat-tab. A more "cleaner" solution is to have a ViewChild for your mat-tab-group and manually update the selected index of your tabGroup inside ngAfterViewInit.

export class TabsComponent implements AfterViewInit {
  @ContentChildren(TabItemComponent) items: QueryList<TabItemComponent>;
  @ViewChild(MatTabGroup) tabGroup: MatTabGroup;
  @Input() selectedIndex = 0; // set as Input() if you want it to be dynamic

  constructor() {}

  ngAfterViewInit() {
    // doesn't work if outside setTimeOut()
    setTimeout(() => {
      this.tabGroup.selectedIndex = this.selectedIndex;
      this.tabGroup.realignInkBar(); // re-align the bottom border of the tab
    });
  }
}
Drei
  • 17
  • 3