Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Tabs SelectedIndex 0 not working

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>
like image 673
amitairos Avatar asked Nov 23 '17 22:11

amitairos


3 Answers

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

<md-tab-group [(selectedIndex)]="value">
like image 84
Fateh Mohamed Avatar answered Oct 25 '22 07:10

Fateh Mohamed


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

like image 23
alex351 Avatar answered Oct 25 '22 05:10

alex351


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
    });
  }
}
like image 27
Drei Avatar answered Oct 25 '22 07:10

Drei