How to Use Material Tabs with Angular 5
I recently wanted to implement tabs in an angular app for a project I’m working on for http://pizzainthecloud.com/ and was excited when I found built in tabs as part of material at: https://material.angular.io/components/tabs/overview. I thought it would be easy.
Was I disappointed! It seems that material is still in something of a state of flux and that most of the information on the web is out of date. So, as I struggled through, I thought I’d share my pains with the world to hopefully prevent others the same difficulties.
As we walk through using material tabs, I’m going to create a demo project to show how this works. If you don’t have angular running, you have to start with https://angular.io/guide/quickstart and then come back.
To start a new project using the CLI, type:
ng new tabdemo
After a minute or so, this should produce a new project in the tabdemo directory. You can then start the project by running:
ng serve --open
How to Use Material Tabs with Angular 5
You should see the default angular application in a new browser window. Now edit your app.component.html in src/app. Remove all of the lines currently there and replace with:
<mat-tab-group> <mat-tab label="One"> <h1>Some tab content</h1> <p>...</p> </mat-tab> <mat-tab label="Two"> <h1>Some more tab content</h1> <p>...</p> </mat-tab> </mat-tab-group>
When you make this edit, your app should break and your test window empty. Our goal is to have these two tabs working by the end of this page.
Now we need to import the modules to make the magic work. Do not believe the docs that say
import {MatTabsModule} from '@angular/material/tabs';
This is a lie, instead add the following two modules to your app.module.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatTabsModule } from '@angular/material';
And then add them to your imports:
imports: [ BrowserModule, BrowserAnimationsModule, MatTabsModule ],
You will get errors because these items are currently in your node_modules. Go to the command prompt and type:
npm install --save @angular/cdk @angular/material
At this point, if you refresh your browser, you should see that tabs are working, but look awful. We can fix that by using a style or you can build one of your own.
My research says there are four pre-defined styles:
deeppurple-amber.css indigo-pink.css pink-bluegrey.css purple-green.css
You can try them all. To add them, you modify your styles.css in your src directory.
@import '@angular/material/prebuilt-themes/indigo-pink.css';
When your browser refreshes, you should see your tabs working.
I hope this helps. Please watch for other articles. Thanks for reading!