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>
it's a bug but you can use 2 ways data binding, it works
<md-tab-group [(selectedIndex)]="value">
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
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
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With