Professional Documents
Culture Documents
Angular Material
Angular Material
#angular-
material2
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Chapter 2: md-autocomplete 7
Introduction 7
Remarks 7
Examples 7
Chapter 3: md-button 16
Introduction 16
Parameters 16
Remarks 16
Examples 16
Simple buttons 16
Chapter 4: md-datepicker 17
Introduction 17
Remarks 17
Examples 17
Chapter 5: md-dialog 22
Introduction 22
Remarks 22
Examples 22
Chapter 6: md-icon 24
Examples 24
Creating an icon 24
Chapter 7: md-table 26
Introduction 26
Remarks 26
Examples 26
Credits 29
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: angular-material2
It is an unofficial and free angular-material2 ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official angular-
material2.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with angular-
material2
Remarks
This section provides an overview of what angular-material2 is, and why a developer might want to
use it.
It should also mention any large subjects within angular-material2, and link out to the related
topics. Since the Documentation for angular-material2 is new, you may need to create initial
versions of those related topics.
Versions
Examples
Installation or Setup with Angular CLI
In this example, we will be using @angular/cli (latest) and the latest version of @angular/material.
You should at least know the basics of Angular 2/4 before continuing the steps below.
https://riptutorial.com/ 2
2.0.0-beta.3
2.0.0-beta.8
2. In your application module import the components which you are going to use:
@NgModule({
imports: [
BrowserAnimationsModule,
MdButtonModule,
MdSnackBarModule,
MdSidenavModule,
CommonModule,
// This is optional unless you want to have routing in your app
// RouterModule.forRoot([
// { path: '', component: HomeView, pathMatch: 'full'}
// ])
],
declarations: [ AppComponent ],
boostrap: [ AppComponent ]
})
export class AppModule {}
You can also easily wrap all angular modules, which you are going to use, into one module:
https://riptutorial.com/ 3
@NgModule({
imports: [
BrowserAnimationsModule,
MdButtonModule,
MdSnackBarModule,
MdSidenavModule
],
exports: [
MdButtonModule,
MdSnackBarModule,
MdSidenavModule
]
})
export class MaterialWrapperModule {}
After that simply import your module into the application main module:
@NgModule({
imports: [
BrowserAnimationsModule,
MaterialWrapperModule,
CommonModule,
// This is optional, use it when you would like routing in your app
// RouterModule.forRoot([
// { path: '', component: HomeView, pathMatch: 'full'}
// ])
],
declarations: [ AppComponent],
bootstrap: [ AppComponent ]
})
export class AppModule {}
This example will be how to install from master and will be using @angular/cli as well.
ng new my-master-app
https://riptutorial.com/ 4
npm install --save @angular/animations
npm install --save angular/material2-builds
npm install --save angular/cdk-builds
Done!
Theme:
A theme is required for material components to work properly within the application.
• deeppurple-amber
• indigo-pink
• pink-bluegrey
• purple-green
If you are using Angular CLI, you can import one of the prebuilt themes in style.css.
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
HammerJS
import 'hammerjs';
Material Icons:
Unless, custom icons provided, Angular Material 2 <md-icon> expects Material Icons.
In index.html add:
https://riptutorial.com/ 5
Read Getting started with angular-material2 online: https://riptutorial.com/angular-
material2/topic/10828/getting-started-with-angular-material2
https://riptutorial.com/ 6
Chapter 2: md-autocomplete
Introduction
This topic includes coding examples related to Angular Material 2 Autocomplete (md-
autocomplete)
Remarks
These examples don't cover all features of md-autocomplete. Please read the documentation
learn more about md-autocomplete.
Examples
Separate control and display
This example shows how to to display specific property in dropdown but bind with the whole
object.
autocomplete-overview-example.html:
<md-input-container>
<input mdInput placeholder="State" [(ngModel)]="selection"
[mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>
autocomplete-overview-example.ts:
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
@Component({
selector: 'autocomplete-overview-example',
templateUrl: 'autocomplete-overview-example.html',
})
export class AutocompleteOverviewExample {
stateCtrl: FormControl;
https://riptutorial.com/ 7
filteredStates: any;
selection: any;
states = [
{ Country: "United States Of America" , CountryID: "1"},
{ Country: "United Kingdom" , CountryID: "2"},
{ Country: "United Arab Emirates" , CountryID: "3"},
];
constructor() {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.startWith(null)
.map(country => country && typeof country === 'object' ? country.Country : country)
.map(name => this.filterStates(name));
}
filterStates(val) {
return val ? this.states.filter(s => s.Country.toLowerCase().indexOf(val.toLowerCase())
=== 0)
: this.states;
}
displayFn(country): string {
console.log(country);
return country ? country.Country : country;
}
Live Example
data.service.ts:
@Injectable()
export class DataService {
fetchData(){
return this.http.get('https://dinstruct-d4b62.firebaseio.com/.json')
.map((res) => res.json())
autocomplete-overview-example.html:
<md-input-container>
https://riptutorial.com/ 8
<input mdInput placeholder="Name" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>
<div>
<h2>Data :</h2>
<span>{{ allSectors | json }}</span>
</div>
autocomplete-overview-example.ts:
@Component({
selector: 'autocomplete-overview-example',
templateUrl: './autocomplete-overview-example.html',
})
export class AutocompleteOverviewExample implements OnInit{
stateCtrl: FormControl;
filteredSectors: any;
allSectors;
ngOnInit(){
this.dataService.fetchData()
.subscribe(
(data) => {
this.allSectors = data.customers;
this.filteredSectors = this.stateCtrl.valueChanges
.startWith(null)
.map(val => val ? this.filter(val) : this.allSectors.slice());
}
);
filter(name) {
return this.allSectors.filter(sector => new RegExp(`^${name}`, 'gi').test(sector.name));
}
displayFn(sector) {
return sector ? sector.name : sector;
}
https://riptutorial.com/ 9
Live Example
This example requires FormsModule and ReactiveFormsModule. Please import them in your
application/module.
input-form-example.html
<p>
<md-input-container class="example-full-width">
<textarea mdInput placeholder="Address" formControlName="address">1600 Amphitheatre
Pkwy</textarea>
</md-input-container>
<md-input-container class="example-full-width">
<textarea mdInput placeholder="Address 2"></textarea>
</md-input-container>
</p>
<td><md-input-container>
<input mdInput placeholder="State"
[mdAutocomplete]="auto"
[formControl]="stateCtrl"
formControlName="state">
</md-input-container></td>
<td><md-input-container class="example-full-width">
<input mdInput #postalCode maxlength="5" placeholder="Postal Code" value="94043"
formControlName="zip">
<md-hint align="end">{{postalCode.value.length}} / 5</md-hint>
</md-input-container></td>
</tr></table>
https://riptutorial.com/ 10
<md-option *ngFor="let state of filteredStates | async" [value]="state"
(onSelectionChange)="selectState(state, addForm.value)">
{{ state }}
</md-option>
</md-autocomplete>
</form>
<p>Form values:</p>
<p>{{ addForm.value | json }}</p>
input-form-example.ts:
@Component({
selector: 'input-form-example',
templateUrl: 'input-form-example.html',
styleUrls: ['input-form-example.css'],
})
export class InputFormExample {
stateCtrl: FormControl;
filteredStates: any;
addForm: FormGroup;
state;
states = [
'Alabama',
'Alaska',
'Arizona',
'Arkansas',
'California',
'Colorado',
'Connecticut',
'Delaware',
'Florida',
'Georgia',
'Hawaii',
'Idaho',
'Illinois',
'Indiana',
'Iowa',
'Kansas',
'Kentucky',
'Louisiana',
'Maine',
'Maryland',
'Massachusetts',
'Michigan',
'Minnesota',
'Mississippi',
'Missouri',
'Montana',
'Nebraska',
'Nevada',
https://riptutorial.com/ 11
'New Hampshire',
'New Jersey',
'New Mexico',
'New York',
'North Carolina',
'North Dakota',
'Ohio',
'Oklahoma',
'Oregon',
'Pennsylvania',
'Rhode Island',
'South Carolina',
'South Dakota',
'Tennessee',
'Texas',
'Utah',
'Vermont',
'Virginia',
'Washington',
'West Virginia',
'Wisconsin',
'Wyoming',
];
this.addForm = this.fb.group({
fname: '',
address: '',
address2: '',
city: '',
"state": this.state,
zip: '',
company: '',
lname: ''
});
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.startWith(null)
.map(name => this.filterStates(name));
}
filterStates(val: string) {
return val ? this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s))
: this.states;
}
submit(form){
alert(JSON.stringify(form));
}
selectState(state, form){
// console.log(state);
// console.log(form);
form.state = state;
}
}
input-form-example.css:
https://riptutorial.com/ 12
.example-form {
width: 500px;
}
.example-full-width {
width: 100%;
}
Live Example
This example requires FormsModule and ReactiveFormsModule. Please import them in your
application/module.
autocomplete-overview-example.html:
<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>
<p></p>
<md-input-container>
<input mdInput placeholder="State2" [mdAutocomplete]="auto" [formControl]="stateCtrl2">
</md-input-container>
<p></p>
<md-input-container>
<input mdInput placeholder="State3" [mdAutocomplete]="auto" [formControl]="stateCtrl3">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete">
<md-option *ngFor="let state of filteredStates | async" [value]="state">
{{ state }}
</md-option>
</md-autocomplete>
autocomplete-overview-example.ts:
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
@Component({
selector: 'autocomplete-overview-example',
templateUrl: 'autocomplete-overview-example.html',
})
export class AutocompleteOverviewExample {
stateCtrl: FormControl;
stateCtrl2: FormControl;
https://riptutorial.com/ 13
stateCtrl3: FormControl;
filteredStates: any;
states = [
'Alabama',
'Alaska',
'Arizona',
'Arkansas',
'California',
'Colorado',
'Connecticut',
'Delaware',
'Florida',
'Georgia',
'Hawaii',
'Idaho',
'Illinois',
'Indiana',
'Iowa',
'Kansas',
'Kentucky',
'Louisiana',
'Maine',
'Maryland',
'Massachusetts',
'Michigan',
'Minnesota',
'Mississippi',
'Missouri',
'Montana',
'Nebraska',
'Nevada',
'New Hampshire',
'New Jersey',
'New Mexico',
'New York',
'North Carolina',
'North Dakota',
'Ohio',
'Oklahoma',
'Oregon',
'Pennsylvania',
'Rhode Island',
'South Carolina',
'South Dakota',
'Tennessee',
'Texas',
'Utah',
'Vermont',
'Virginia',
'Washington',
'West Virginia',
'Wisconsin',
'Wyoming',
];
constructor() {
this.stateCtrl = new FormControl();
this.stateCtrl2 = new FormControl();
this.stateCtrl3 = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
https://riptutorial.com/ 14
.startWith(null)
.map(name => this.filterStates(name));
this.filteredStates = this.stateCtrl2.valueChanges
.startWith(null)
.map(name => this.filterStates(name));
this.filteredStates = this.stateCtrl3.valueChanges
.startWith(null)
.map(name => this.filterStates(name));
}
filterStates(val: string) {
return val ? this.states.filter(s => s.toLowerCase().indexOf(val.toLowerCase()) === 0)
: this.states;
}
Live Example
https://riptutorial.com/ 15
Chapter 3: md-button
Introduction
This topic includes examples on how to create a button and what its' directives and other stuff do.
Parameters
Attribute Description
md-raised-
button Creates a rectangular button w/ elevation
Remarks
For more information and more examples, visit the docs.
Examples
Simple buttons
To create a button, use the md-button attribute for a flat button and md-raised-button for an elevated
button:
<button md-button>Button</button>
<button md-raised-button>Raised Button</button>
<button md-fab><md-icon>add</md-icon></button>
<button md-mini-fab><md-icon>check</md-icon></button>
<button md-icon-button><md-icon>person_add</md-icon></button>
Plunker Demo
https://riptutorial.com/ 16
Chapter 4: md-datepicker
Introduction
This topic focuses on examples related to md-datepicker.
Remarks
For more details, please check the md-datepicker documentation here.
Examples
Data binding with md-datapicker
datepicker-overview-example.html:
<md-input-container>
<input mdInput
[mdDatepicker]="picker"
[(ngModel)]="date"
placeholder="Choose a date">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
<div>
Date Chosen using 'ngModel':
<div>{{ date }}</div>
</div>
datepicker-overview-example.ts:
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html'
})
export class DatepickerOverviewExample implements OnInit {
date;
ngOnInit(){
this.date = new Date();
}
Live demo
https://riptutorial.com/ 17
datepicker-overview-example.html:
<md-input-container>
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="value">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker [startAt]="startDate" (selectedChanged)="selectedDate($event)"></md-
datepicker>
datepicker-overview-example.ts:
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html'
})
export class DatepickerOverviewExample {
checkDate: Date;
selectedDate(date){
// ngModel still returns the old value
console.log("ngModel: " + this.value);
Live demo
• min
• max
• startAt
• startView
• touchUi
datepicker-overview-example.html:
<h2>Options</h2>
<p>
<md-checkbox [(ngModel)]="touch">Use touch UI</md-checkbox>
<md-checkbox [(ngModel)]="filterOdd">Filter odd months and dates</md-checkbox>
https://riptutorial.com/ 18
<md-checkbox [(ngModel)]="yearView">Start in year view</md-checkbox>
</p>
<p>
<md-input-container>
<input mdInput [mdDatepicker]="minDatePicker" [(ngModel)]="minDate" placeholder="Min date"
(keydown)="false" (click)="minDatePicker.open()">
<button mdSuffix [mdDatepickerToggle]="minDatePicker"></button>
</md-input-container>
<md-datepicker #minDatePicker [touchUi]="touch"></md-datepicker>
<md-input-container>
<input mdInput [mdDatepicker]="maxDatePicker" [(ngModel)]="maxDate" placeholder="Max date"
(keydown)="false" (focus)="maxDatePicker.open()">
<button mdSuffix [mdDatepickerToggle]="maxDatePicker"></button>
</md-input-container>
<md-datepicker #maxDatePicker [touchUi]="touch"></md-datepicker>
</p>
<p>
<md-input-container>
<input mdInput [mdDatepicker]="startAtPicker" [(ngModel)]="startAt" placeholder="Start at
date" (keydown)="false" (focus)="startAtPicker.open()">
<button mdSuffix [mdDatepickerToggle]="startAtPicker"></button>
</md-input-container>
<md-datepicker #startAtPicker [touchUi]="touch"></md-datepicker>
</p>
<h2>Result</h2>
<p>
<button [mdDatepickerToggle]="resultPicker"></button>
<md-input-container>
<input mdInput
#resultPickerModel="ngModel"
[mdDatepicker]="resultPicker"
[(ngModel)]="date"
[min]="minDate"
[max]="maxDate"
[mdDatepickerFilter]="filterOdd ? dateFilter : null"
placeholder="Pick a date"
(keydown)="false"
(focus)="resultPicker.open()">
<md-error *ngIf="resultPickerModel.hasError('mdDatepickerMin')">Too early!</md-error>
<md-error *ngIf="resultPickerModel.hasError('mdDatepickerMax')">Too late!</md-error>
<md-error *ngIf="resultPickerModel.hasError('mdDatepickerFilter')">Date unavailable!</md-
error>
</md-input-container>
<md-datepicker
#resultPicker
[touchUi]="touch"
[startAt]="startAt"
[startView]="yearView ? 'year' : 'month'">
</md-datepicker>
</p>
<p>
<input [mdDatepicker]="resultPicker2"
[(ngModel)]="date"
[min]="minDate"
[max]="maxDate"
[mdDatepickerFilter]="filterOdd ? dateFilter : null"
(focus)="resultPicker2.open()"
placeholder="Pick a date"
(keydown)="false">
https://riptutorial.com/ 19
<button [mdDatepickerToggle]="resultPicker2"></button>
<md-datepicker
#resultPicker2
[touchUi]="touch"
[startAt]="startAt"
[startView]="yearView ? 'year' : 'month'">
</md-datepicker>
</p>
datepicker-overview-example.ts:
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html'
})
export class DatepickerOverviewExample implements OnInit {
touch: boolean;
filterOdd: boolean;
yearView: boolean;
minDate: Date;
maxDate: Date;
startAt: Date;
date: Date;
dateFilter = (date: Date) => date.getMonth() % 2 == 1 && date.getDate() % 2 == 0;
Live demo
datepicker.component.html:
<md-input-container>
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
<p></p>
<div>
<button md-raised-button (click)="setLocale('en')">English - US</button>
https://riptutorial.com/ 20
<button md-raised-button (click)="setLocale('bn')">Bengali</button>
datepicker.component.ts:
@Component({
selector: 'datepicker-overview-example',
templateUrl: './datepicker-overview-example.html',
styleUrls: ['./datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {
setLocale(val){
console.log(val);
this.dateAdapter.setLocale(val);
}
Live demo
https://riptutorial.com/ 21
Chapter 5: md-dialog
Introduction
This topic includes examples of md-dialog.
Remarks
To find more details on md-dialog, please check the documentation here.
Examples
Initialize md-dialog with data passed from parent component
This example requires MdDialogRef and MD_DIALOG_DATA. Please import them in the component
module.
input-overview-example.html:
<md-input-container>
<input mdInput
[(ngModel)]="id"
placeholder="Value passed to md-dialog">
</md-input-container>
<p></p>
<button md-raised-button
(click)="openDialog(id)">
Open Dialog
</button>
input-overview-example.ts:
@Component({
selector: 'input-overview-example',
templateUrl: 'input-overview-example.html'
})
export class InputOverviewExample {
id: any;
https://riptutorial.com/ 22
openDialog(value) {
let dialogRef = this.dialog.open(DialogResultExampleDialog, {
data: {
id: value
}
});
dialogRef.afterClosed().subscribe(result => {
console.log(result);
});
}
}
@Component({
selector: 'dialog-result-example-dialog',
template: `<p md-dialog-title>Confirm Toggle </p>
<p md-dialog-content>Id passed from component: {{ this.passedId }}</p>
<md-dialog-actions>
<button md-button color="primary"
(click)="dialogRef.close('Cancel')">Cancel</button>
<button md-button color="primary"
(click)="dialogRef.close('continue')">Continue</button>
</md-dialog-actions>
`,
})
export class DialogResultExampleDialog implements OnInit {
passedId: string;
ngOnInit(){
this.passedId = this.data.id;
}
}
Live demo
https://riptutorial.com/ 23
Chapter 6: md-icon
Examples
Creating an icon
The following is a guide on how to create an icon from material design icons:
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');
2. Use it as follows:
<md-icon>menu</md-icon>
You're done!
1. Download the SVG iconset / icon (in this case, we're getting the icons from
https://materialdesignicons.com/getting-started.
2. Save it under your assets folder or somewhere else which you can access with.
mdIconRegistry.addSvgIconSet(domSanitizer.bypassSecurityTrustResourceUrl('assets/icons.svg'))
}
}
https://riptutorial.com/ 24
<md-icon svgIcon="menu"></md-icon>
https://riptutorial.com/ 25
Chapter 7: md-table
Introduction
This topic includes examples related to md-table
Remarks
For more details on md-table please check the documentation
Examples
Connect DataSource from external API
This example uses InMemoryDbService from angular-in-memory-web-api to provide the JSON data
from mock API.
Live demo
service.ts:
@Injectable()
export class AppState {
fetchFilterFields() {
console.log(this.apiUrl);
return this.http.get(this.apiUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
component.ts:
https://riptutorial.com/ 26
import {Component} from '@angular/core';
import {DataSource} from '@angular/cdk';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/merge';
@Component({
selector: 'md-table-example',
templateUrl: 'select-form-example.html',
styleUrls: ['select-form-example.css']
})
export class SelectFormExample implements OnInit {
ngOnInit(){
this.dataSource = new ExampleDataSource(this.appState);
}
connect(): Observable<Hero[]> {
console.log('connect');
if (!this.subject.isStopped)
this.appState.fetchFilterFields()
.then(res => {
this.subject.next(res)
});
return Observable.merge(this.subject);
}
disconnect() {
this.subject.complete();
this.subject.observers = [];
}
}
component.html:
https://riptutorial.com/ 27
<!-- ID Column -->
<ng-container cdkColumnDef="id">
<md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>
<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
</div>
For reference:
in-memory-data-service.ts:
https://riptutorial.com/ 28
Credits
S.
Chapters Contributors
No
2 md-autocomplete Nehal
3 md-button Edric
4 md-datepicker Nehal
5 md-dialog Nehal
6 md-icon Edric
7 md-table Nehal
https://riptutorial.com/ 29