Angular Material Tabs

In this lecture let's take a look about tabs in angular material, tabs basically allow you to organize content into separate views where only one view can be visible at a given time.

First step let's import the MatTabModule from @angular/material in material.module.ts and add it to MaterialComponents[] array.

import { MatTabsModule } frm '@angular/material';

MaterialComponents = [
    MatTabsModule
]

Now we can create tabs in the HTML the component is mat-tab-group with this component each tab is represented using the mat-tab component.

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

each tab will have a label and the content let's add the labels and the content.

<mat-tab-group>
  <mat-tab label="Angular">Angular Content</mat-tab>
  <mat-tab label="React">React Content</mat-tab>
  <mat-tab label="VueJs">VueJs Content</mat-tab>
</mat-tab-group>

Now if you save the files and take a look the browser. angular material tabs

You should see 3 tabs, if you want to know which tab is active at any point of time you can use the selectedIndex property. So back in HTML add a template reference variable on mat-tab-goup and then we can use interpolation to view the property value.

<mat-tab-group #tabRef>
  <mat-tab label="Angular">Angular Content</mat-tab>
  <mat-tab label="React">React Content</mat-tab>
  <mat-tab label="VueJs">VueJs Content</mat-tab>
</mat-tab-group>
{{ tabRef.selectedIndex }}

If you save and take look at the browser you can see that initially it displays 0 because index starts from 0, click on React it changes to 1 and VueJs changes to 2.

Now if you want to perform some operations when you're changing tabs you can listen to the selectedTabChange event, so back in the HTML bind to selectedTabChange and as an event handler let's call logChange(tabRef.selectedIndex) and pass in the selected index, notice that the logChange(index) is a function that we defined in app.component.ts.

logChange(index){
    console.log(index);
}

So here is the HTML code for this event handler.

<mat-tab-group #tabRef (selectedTabChange)="logChange(tabRef.selectedIndex)">
  <mat-tab label="Angular">Angular Content</mat-tab>
  <mat-tab label="React">React Content</mat-tab>
  <mat-tab label="VueJs">VueJs Content</mat-tab>
</mat-tab-group>

Back to the browser and open the console and change the tabs you can see the selectedIndex being logged. angular material tabs selectedTabChange When the tab changes you can perform any operation you want to using the selectedTabChange event .

So that is a quick look at tabs in angular material.