How to Set Default Tab in Angular?


How to Set Default Tab in Angular? How to change tab in mat-tab-group using selectedIndex dynamically.

Source code from this tutorial can be found at GitHub.

Previously you saw how to create tabs in Angular using Angular Material. Now let’s see how you can set a default tab.

This is how the app.component.html file looks:

<div class="container">
  <mat-tab-group mat-align-tabs="start">
    <mat-tab label="New Employee" >

    </mat-tab>
    <mat-tab label="All Employees" >

    </mat-tab>
  </mat-tab-group>
</div>

You can use selectedIndex property to set the default tab on the tab group.

<div class="container">
  <mat-tab-group mat-align-tabs="start" [selectedIndex]="0">
    <mat-tab label="New Employee" >

    </mat-tab>
    <mat-tab label="All Employees" >

    </mat-tab>
  </mat-tab-group>
</div>

Setting selectedIndex property as 0 sets the first tab and setting it as 1 sets the second tab.

Let’s create an enum for the Tabs in the app.component.ts.

enum Tabs{
  New_Employees = 0,
  All_Employees = 1
}

Set a variable called tabIndex for the selectedIndex in the mat-tab-group.

<div class="container">
  <mat-tab-group mat-align-tabs="start" [selectedIndex]="tabIndex">
    <mat-tab label="New Employee" >

    </mat-tab>
    <mat-tab label="All Employees" >

    </mat-tab>
  </mat-tab-group>
</div>

Declare the tabIndex variable in app.component.ts and define a method called setTab to change the selected tab.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'material-tabs';

  tabIndex : Tabs = Tabs.New_Employees;

  ngOnInit(){
    this.setTab(Tabs.All_Employees);
  }

  setTab(tab : Tabs){
    this.tabIndex = tab; 
  }
}

enum Tabs{
  New_Employees = 0,
  All_Employees = 1
}

As seen in the above code, on ngOnInit you have called the setTab method to set the default tab to All_Employees.

Save the above changes and refresh the application. You should be able to see the second tab All Employees selected by default.