Angular Material Tutorial with examples

Angular Material module helps us to create high-quality UI applications with Angular framework by following Material Design specifications.

In this Angular material tutorial I will explain basics of Angular Material with simple examples,starting from setting up Angular material project in our local machine.

Angular Material project is under active development. New features are being added regularly.Official latest version of Angular Material is 15.0.

What is Angular Material?

In 2014 Google I/O conference Google announced their new design language called Material Design.

Most of the Android apps like Gmail, Youtube, Google Drive etc developed based on this Material Design spec.

Now with this Angular Material project, we can develop Material Design components for web and mobile browsers.

Creating Angular Material Project

We will create a new project in our local development environment called Angular-Material-tutorial with Angular CLI command. as mentioned in above tutorial setup your local development environment.

ng new Angular-Material-tutorial

Now navigate to Angular-Material project folder.

cd Angular-Material-tutorial

Installing Angular Material and Angular CDK Modules

Make sure you install NodeJs in your systems. NodeJs is required to develop Angular Apps.

Install Angular Material and Angular CDK modules by using below node command.

npm install --save @angular/material @angular/cdk @angular/core @angular/common

After successful installation, you can see them in _nodemodules folder as shown below. And inside the material folder, we can see different UI components like buttons, bundles, autocomplete etc.

hello
hello

Installing Angular Animations Module

Few Material components depend upon Angular Animations modules. Install Angular Animation module with the below command.

npm install --save @angular/animations

Install HammerJS for Gesture Support

Some Angular Material components like mat-slider, matTooltip,mat-slide-toggle rely on HammerJS for gestures.

npm install --save hammerjs

After successful installation, add the reference of HammerJS in angular-cli.json file

"scripts": [
"../node_modules/hammerjs/hammer.min.js"
]

Adding a Pre-built Angular Material Theme

When we install Angular Material few pre-built themes are being installed automatically. Available pre-built themes are 1. indigo-pink 2. deeppurple-amber 3. purple-green 4. pink-bluegrey

Add the theme to global style.css

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Adding Angular Material Icons

If you want to use Material icons, load the official icon fonts in index.html file.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Then we can mat-icon component tag to display named icons

<mat-icon>favorite</mat-icon> //Displays love symbol

Now we will add a Material Module in our project.

Complete Angular Material Icon List

Adding a Custom Angular Material Module

Create a new material module by using following angular-cli command

ng generate module material

We will use following material UI components in our project

  1. MatButtonModule
  2. MatToolbarModule
  3. MatIconModule
  4. MatCardModule

Add them in material.module.ts file

import { NgModule } from '@angular/core';

import {

MatButtonModule,
MatToolbarModule,
MatIconModule,
MatCardModule

} from '@angular/material';

@NgModule({

imports: [

MatButtonModule,
MatToolbarModule,
MatIconModule,
MatCardModule

],

exports: [

MatButtonModule,
MatToolbarModule,
MatIconModule,
MatCardModule

]

})

export class MaterialModule {}

I have added them in exports to use them in other modules.

Now our Material Module is ready we will use it in our default app module. Add the MaterialModule in app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { MaterialModule } from './material/material.module';
import { BrowserAnimationsModule } 
       from '@angular/platform-browser/animations';

import { AppComponent } from './app.component';

@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule,
FormsModule,
HttpModule,
MaterialModule,
BrowserAnimationsModule 

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Make sure you add it after BrowserModule because Material components depend upon BrowserModule. I have added BrowserAnimationModule to support animations.

Angular Material is ready. Now will use available Angular Material components in our template file

I have used <mat-toolbar> <mat-card> and mat-button components in this project. Add the following code in app.component.html file.

<div id="material-example">
   
  <h1>ToolBar</h1>
   
  <mat-toolbar color="primary">
     
        <span>Material Design Rocks!</span>
   
  </mat-toolbar>
   
   <br/>
   
   <h1>Buttons</h1>

 <mat-card>

  <button mat-button>Basic</button>
  <button mat-raised-button>Raised</button>
  <button mat-icon-button><mat-icon>favorite</mat-icon></button>
  <button mat-fab>Fab</button>
  <button mat-mini-fab>mFab</button>

</mat-card>

</div>

I added different types of buttons like basic (mat-button) , Raised (mat-raised-button), icon button(mat-icon-button),fab button (mat-fab) and mini-fab button (mat-mini-fab).

Now open the command prompt and type ng serve command after successful compilation browse http://localhost:4200 to load the Angular Material Project.

hello

List of Available UI components in Angular Material

We can learn how to write Angular code by following best principles with the help of Angular Material UI components

Here is the list of UI components available in Angular Material project.

Angular Material Form Components List

Form ComponentsExample
Autocomplete<mat-form-field> <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option> </mat-autocomplete>
Checkbox<mat-checkbox>Check me!</mat-checkbox>
Datepicker<input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker>
Form field<mat-form-field> <input matInput placeholder="Input"> </mat-form-field>
Input<mat-form-field class="example-width"> <textarea matInput placeholder="Leave a comment"></textarea> </mat-form-field>
Radio button<mat-radio-group> <mat-radio-button value="1">Option 1</mat-radio-button> <mat-radio-button value="2">Option 2</mat-radio-button> </mat-radio-group>
Select<mat-select placeholder="Select City"> <mat-option *ngFor="let city of cities" [value]="city.id"> {{city.name}} </mat-option> </mat-select>
Slider<mat-slider></mat-slider>
Slide toggle<mat-slide-toggle>Slide me!</mat-slide-toggle>

Angular Material Navigation Components List

Navigation ComponentsDescription
Menu<button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-menu #menu="matMenu"> <button mat-menu-item>Item 1</button> <button mat-menu-item>Item 2</button> </mat-menu>
Side Nav<mat-sidenav-container> <mat-sidenav mode="side" opened>Sidenav content</mat-sidenav> <mat-sidenav-content>Main content</mat-sidenav-content> </mat-sidenav-container>
Toolbar<mat-toolbar>Toolbar</mat-toolbar>

Angular Material Layout Components List

layout ComponentsExample
Card<mat-card>Simple card</mat-card>
Divider<mat-divider></mat-divider>
Expansion Panel<mat-expansion-panel> <mat-expansion-panel-header> <mat-panel-title> Panel Title </mat-panel-title> <mat-panel-description> panel Description </mat-panel-description> </mat-expansion-panel-header> <p>I'm visible When opened</p> </mat-expansion-panel>
Grid list<mat-grid-list> <mat-grid-tile>1</mat-grid-tile> <mat-grid-tile>2</mat-grid-tile> </mat-grid-list>
List<mat-list role="list"> <mat-list-item role="listitem">Item 1</mat-list-item> <mat-list-item role="listitem">Item 2</mat-list-item> </mat-list>
Stepper<mat-horizontal-stepper> <mat-step> Step 1 </mat-step> <mat-step> Step 2 </mat-step> <mat-step> Done </mat-step> </mat-horizontal-stepper>
Tabs<mat-tab-group> <mat-tab label="First"> Tab 1 </mat-tab> <mat-tab label="Second"> Tab 2 </mat-tab> <mat-tab label="Third"> Tab 3 </mat-tab> </mat-tab-group>
Tree<mat-tree> <mat-tree-node> parent</mat-tree-node> <mat-tree-node> -- child1 </mat-tree-node> <mat-tree-node> -- child2 </mat-tree-node> </mat-tree>

Angular Material Buttons & indicators Components

Buttons& indicatorsExample
Button<button mat-button>Click me!</button>
Button toggle<mat-button-toggle-group name="fontStyle" aria-label="Font Style"> <mat-button-toggle value="bold">Bold</mat-button-toggle> <mat-button-toggle value="italic">Italic</mat-button-toggle> <mat-button-toggle value="underline">Underline</mat-button-toggle> </mat-button-toggle-group>
Badge<p matBadge="4" matBadgeOverlap="false">Text with a badge</p>
Chips<mat-chip-list> <mat-chip>Chip 1</mat-chip> <mat-chip>Chip 2</mat-chip> <mat-chip>Chip 3</mat-chip> </mat-chip-list>
Icon<mat-icon>home</mat-icon>
Progress spinner<mat-spinner></mat-spinner>
Progress bar<mat-progress-bar mode="determinate" value="40"></mat-progress-bar>
Ripples<div matRipple [matRippleCentered]="centered" [matRippleDisabled]="disabled" [matRippleUnbounded]="unbounded" [matRippleRadius]="radius" [matRippleColor]="color"> Click me </div>

Angular Material Popups & modals Components

popups & modalsExample
Bottom Sheetconst bottomSheetRef = bottomSheet.open(SocialShareComponent, { ariaLabel: 'Share on social media' });
Dialoglet dialogRef = dialog.open(UserProfileComponent, { height: '400px', width: '600px', });
Snackbarlet snackBarRef = snackBar.open('Message archived');
Tooltip<button mat-raised-button matTooltip="Tooltip Action" > Tooltip </button>

Angular Material DataTable Components

DataTable ComponentsExample
Paginator<mat-paginator [length]="100" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100]"> </mat-paginator>
Sort Header<table matSort (matSortChange)="sortData($event)"> <tr> <th mat-sort-header="name">name</th> <th mat-sort-header="id">id</th> </tr> <tr *ngFor="let item of sortedData"> <td>{{item.name}}</td> <td>{{item.id}} </tr> </table>
Table<table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef>id</th> <td mat-cell *matCellDef="let element"> {{element.id}} </td> </ng-container> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef> Name </th> <td mat-cell *matCellDef="let element"> {{element.name}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>

Angular Material components Browser support

Angular Material components will work in most of the modern web browsers like Chrome (Android as well), Mozilla, Safari (IOS as well), and IE11/Edge.

Download Source Code

Common errors while setting up Angular Material project:

As Angular and Angular Material projects are receiving continuous updates you might run into few problems setting up Angular Material in your local machine.

You might get few errors if the version of Angular Material not align with the angular core modules versions

@angular/material/expansion/typings/index.d.ts, found version 4, expected 3

If angular is already installed in your local machine and if it is not the latest version. If you try to install Angular Material you will get following warnings.

npm i -g @angular/material
npm WARN @angular/material@6.1.0 requires a peer of @angular/cdk@6.1.0 but none
is installed. You must install peer dependencies yourself.
npm WARN @angular/material@6.1.0 requires a peer of @angular/core@>=6.0.0-beta.0
<7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/material@6.1.0 requires a peer of @angular/common@>=6.0.0-beta
.0 <7.0.0 but none is installed. You must install peer dependencies yourself.

Latest Angular Material Module depend upon Angular CDK,Angular Core and Angular Common modules.

So its always better to install these three modules together.

npm install @angular/material @angular/cdk @angular/core @angular/common

And further @angular/core has a dependency on reactive js and zone.js modules. Install both modules using below command

npm install rxjs zone.js