Home  >  Angular  >  Angular Material

Angular Material Checkbox Example

By Arvind Rai, September 17, 2017
This page will walk through Angular Material checkbox example. Angular Material provides MdCheckbox directive which has <md-checkbox> selector. <md-checkbox> provides the same functionality as native <input type="checkbox"> enhanced with Material Design styling and animations. <md-checkbox> can handle checkbox label, working with forms, indeterminate state, theming, accessibility and all native functionalities. <md-checkbox> provides properties such as indeterminate, checked, labelPosition, change etc. MdCheckbox also provides methods such as toggle(), focus(). <md-checkbox> can be used with template-driven forms as well as reactive forms. The color of <md-checkbox> is changed by using color property. Here on this page we will provide steps to install Angular Material and complete example to work with <md-checkbox>.

Technologies Used

Find the technologies being used in our example.
1. Angular 4.2.4
1. Angular Material 2.0.0-beta.10
2. TypeScript 2.3.3
3. Node.js 6.10.1
4. Angular CLI 1.3.1
5. Angular Compiler CLI 4.2.4

Project Structure

Find the project structure of our demo application.
angular-demo
|
|--src
|   |
|   |--app 
|   |   |
|   |   |--md-checkbox-demo.component.ts
|   |   |--md-checkbox-demo.component.html
|   |   |--template-driven-form.component.ts
|   |   |--template-driven-form.component.html
|   |   |--reactive-form.component.ts
|   |   |--reactive-form.component.html
|   |   |--user.ts
|   |   |--user-service.ts
|   |   |
|   |   |--app.component.ts
|   |   |--app.module.ts 
|   |   
|   |--main.ts
|   |--index.html
|   |--styles.css
|
|--node_modules
|--package.json 

Install Angular Material

To use Angular with Angular Material, we need to follow below steps.
1. Install Angular CLI using the link .
2. Now to install Angular Material, go to the project home directory using command prompt where package.json is located and run following command.
npm install --save @angular/material @angular/cdk 
3. If animation is not already installed, we need to install it using following command.
npm install --save @angular/animations 
4. Now include a theme. Import the following CSS into styles.css file.
@import "~@angular/material/prebuilt-themes/indigo-pink.css"; 
5. Some Angular Material components uses hammerjs. To install it use following command.
npm install --save hammerjs 
Now go to src/main.ts and import it as follows.
import 'hammerjs'; 
6. To add material icon, we can use following link in our index.html.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> 

Find the reference link to install Angular Material.

Import MdCheckboxModule and BrowserAnimationsModule in Application Module

To work with Angular Material checkbox we need to import MdCheckboxModule and BrowserAnimationsModule in our application module.
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MdCheckboxModule } from '@angular/material';

@NgModule({
  imports: [  
    ------
    BrowserAnimationsModule, 
    MdCheckboxModule 
  ],
  ------
})
export class AppModule { } 
In the same way we can import other Angular Material modules.
To work with button, import MdButtonModule
To work with input, import MdInputModule
To work with table, import MdTableModule

MdCheckbox Directive: <md-checkbox> Selector

MdCheckbox has <md-checkbox> selector. It supports all the functionalities of HTML 5 checkbox. It can have following states i.e. checked, unchecked, indeterminate or disabled. Here we will discuss methods and some of its properties.
Input Properties: indeterminate, checked, labelPosition, required, color etc.
Output Properties: indeterminateChange, change etc.
Methods: toggle(), focus()

Find the link for complete description of Angular Material checkbox API.

<md-checkbox> is used as following.
<md-checkbox>Check me</md-checkbox> 
Now find the example.
md-checkbox-demo.component.html
<h3>MdCheckbox Demo</h3>

<md-checkbox (change)="onChkChange()">change test</md-checkbox>

<br/><br/>

<md-checkbox [checked]="isChecked">checked test</md-checkbox>

<br/>{{isChecked}}
<br/><br/>

<md-checkbox [(indeterminate)]="isIndeterminate">indeterminate test</md-checkbox>

<br/>{{isIndeterminate}}
<br/><br/>

<md-checkbox [labelPosition]="chkLabelPosition">Label Position test</md-checkbox>

<br/>{{chkLabelPosition}}
<br/><br/>

<md-checkbox color="primary">primary color test</md-checkbox>
<br/>
<md-checkbox color="warn">warn color test</md-checkbox>

<br/><br/>

<md-checkbox [(ngModel)]= "isChecked">ngModel test</md-checkbox>

<br/><br/>

<md-checkbox #tgchk>toggle() test</md-checkbox>

<br/><br/>

<md-checkbox #fschk>focus() test</md-checkbox> 
md-checkbox-demo.component.ts
import { Component, ViewChild } from '@angular/core';
import { MdCheckbox } from '@angular/material';

@Component({
   selector: 'app-md-checkbox-demo',
   templateUrl: './md-checkbox-demo.component.html'
})
export class MDCheckboxDemoComponent { 
   @ViewChild('tgchk')
   toggleChk: MdCheckbox;
   
   @ViewChild('fschk')
   focusChk: MdCheckbox;
   
   isIndeterminate = false;
   isChecked = false;
   chkLabelPosition = 'after';
   onChkChange() {
	   console.log('Checked value changed.');
	   this.isChecked = (this.isChecked === true )? false : true;
	   this.isIndeterminate = (this.isIndeterminate === true )? false : true;
	   this.chkLabelPosition = (this.chkLabelPosition === 'after' )? 'before' : 'after';
	   
	   this.toggleChk.toggle();
	   this.focusChk.focus();
   }
} 
Find the print screen of the output.
Angular Material Checkbox Example

change

change is an event and will emit when checked value of checkbox is changed. We use it as follows.
<md-checkbox (change)="onChkChange()">change test</md-checkbox> 
For every check/uncheck onChkChange() will be called.
onChkChange() {
   console.log('Checked value changed.');
} 

checked

checked can make a checkbox checked/unchecked. Find the example.
<md-checkbox [checked]="isChecked">checked test</md-checkbox> 
When the value of isChecked is true then, checkbox will be checked. When the value of isChecked is false then, checkbox will be unchecked.

indeterminate

indeterminate can make a checkbox indeterminate. This is also called 'mixed' mode. Whenever checkbox is manually clicked, indeterminate is immediately set to false. MdCheckbox also provides indeterminateChange. So we can use indeterminate as two-way binding. It is used as follows.
<md-checkbox [(indeterminate)]="isIndeterminate">indeterminate test</md-checkbox> 
When the value of isIndeterminate is true, checkbox will be indeterminate.

labelPosition

labelPosition decides label position. The values of labelPosition is before and after. Default value is after.
<md-checkbox labelPosition="after">After Label Position test</md-checkbox>
<md-checkbox labelPosition="before">Before Label Position test</md-checkbox> 

Theme: color

<md-checkbox> can change its color by using color property. The default color of checkbox is accent color of theme. The values of color can be primary or warn also.
<md-checkbox color="primary">primary color test</md-checkbox>
<md-checkbox color="warn">warn color test</md-checkbox> 

<md-checkbox> with ngModel

<md-checkbox> can be bound with ngModel. Find the example.
<md-checkbox [(ngModel)]= "isChecked">ngModel test</md-checkbox> 
When isChecked is true, checkbox will be checked and when isChecked is false, checkbox will be unchecked.

toggle()

toggle() method toggles the checked state of checkbox. To use toggle() method, first create a checkbox and assign a local template variable as given below.
<md-checkbox #tgchk>toggle() test</md-checkbox> 
Now create the instance of MdCheckbox using @ViewChild and passing the local template variable of the checkbox.
@ViewChild('tgchk')
toggleChk: MdCheckbox; 
To toggle the checked state of the checkbox, now call toggle() method as given below.
this.toggleChk.toggle(); 

focus()

focus() method focuses the checkbox. To use focus() method, first create a checkbox and assign a local template variable as given below.
<md-checkbox #fschk>focus() test</md-checkbox> 
Now create the instance of MdCheckbox using @ViewChild and passing the local template variable of the checkbox.
@ViewChild('fschk')
focusChk: MdCheckbox; 
To focus the checkbox, now call focus() method as given below.
this.focusChk.focus(); 

Validate <md-checkbox>

Suppose we want to validate checkbox to be required check, we need to use required property as given below.
<md-checkbox name="tc" [ngModel]="user.isTCAccepted" required #tc="ngModel">
               Accept T & C</md-checkbox> 
We can use validation properties valid, invalid etc using local template variable as given below.
<div *ngIf="tc.invalid" [ngClass] = "'error'"> 
     Accept T & C.
</div> 

<md-checkbox> with Template-Driven Forms

Here we will create template-driven from that will use Angular material checkbox, input and button. We will validate form and fetch its values.
template-driven-form.component.html
<h3>Template Driven Form with MdCheckbox</h3>
<p *ngIf="isValidFormSubmitted" [ngClass] = "'success'">
    Form submitted successfully.
</p>
<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
  <table md-table>
	 <tr> 
	   <td> 
	          <input mdInput placeholder="Enter name" name="uname" [ngModel]="user.userName" required #uname="ngModel">
		  <div *ngIf="uname.invalid && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> 
		     Name required. 
		  </div>
	   </td>
	 </tr> 
	 <tr>
	  <td>
	   <md-checkbox name="married" [ngModel]="user.isMarried" color="primary">Are you married?</md-checkbox>
	  </td>
	 </tr>	 
	 <tr>
	  <td>
	         <md-checkbox name="tc" [ngModel]="user.isTCAccepted" required #tc="ngModel">Accept T & C</md-checkbox>
		 <div *ngIf="tc.invalid && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> 
		     Accept T & C.
		 </div>
	  </td>
	 </tr>		 
	 <tr> 	  
	   <td>
	         <button md-raised-button color="primary">Submit</button>
		 <button type="button" md-raised-button color="accent" (click)="setDefaultValues()">Set Default</button>
		 <button type="button" md-raised-button color="warn" (click)="resetForm(userForm)">Reset</button>		  
	   </td>
	 </tr>	   
  </table>  
</form> 
template-driven-form.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

import { UserService } from './user-service';
import { User } from './user';

@Component({
   selector: 'app-template',
   templateUrl: './template-driven-form.component.html'
})
export class TemplateDrivenFormComponent { 
        isValidFormSubmitted = false;
	user = new User();
	constructor(private userService: UserService) {
	}
	onFormSubmit(form: NgForm) {
	   this.isValidFormSubmitted = false;
	   if(form.invalid){
		  return;	
	   } 	
	   this.isValidFormSubmitted = true;
	   this.user.userName = form.controls['uname'].value;
	   this.user.isMarried = form.controls['married'].value;
	   this.user.isTCAccepted = form.controls['tc'].value;
	   this.userService.createUser(this.user);
	   this.resetForm(form);
	}
	resetForm(form: NgForm) {
	   form.resetForm({
		   married: false
	   });	
	}
	setDefaultValues() {
	   this.user.userName = 'Krishna';
	   this.user.isMarried = true;
	   this.user.isTCAccepted = false;
	}
} 
user.ts
export class User { 
        userName: string;
	isMarried: boolean = false;
	isTCAccepted: boolean;
}
user-service.ts
import { Injectable } from '@angular/core';

import { User } from './user';

@Injectable()
export class UserService {
   createUser(user: User) {
       //Log user data in console
       console.log("User Name: " + user.userName);
       console.log("Married?: " + user.isMarried);
       console.log("T & C accepted?: " + user.isTCAccepted);
   }   
} 

<md-checkbox> with Reactive Forms

Here we will create reactive from that will use Angular material checkbox, input and button. We will validate form and fetch its values.
reactive-form.component.html
<h3>Reactive Form  with MdCheckbox</h3>
<p *ngIf="isValidFormSubmitted && userForm.pristine" [ngClass] = "'success'">
    Form submitted successfully.
</p>
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
  <table>
	 <tr> 
	   <td> 
	          <input mdInput placeholder="Enter name" formControlName="uname">
		  <div *ngIf="userForm.get('uname').invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> 
		      Name required. 
		  </div>
	   </td>
	 </tr> 
	 <tr>
	  <td>
	   <md-checkbox formControlName="married">Are you married?</md-checkbox>
	  </td>
	 </tr>	 
	 <tr>
	  <td>
	         <md-checkbox formControlName="tc">Accept T & C</md-checkbox>
		 <div *ngIf="userForm.get('tc').invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> 
		     Accept T & C.
		 </div>		 
	  </td>
	 </tr>		 
	 <tr> 	  
	   <td>
	         <button md-raised-button color="primary">Submit</button>
		 <button md-raised-button color="accent" type="button" (click)="setDefaultValues()">Set Default</button>
		 <button md-raised-button color="warn" type="button" (click)="reset()">Reset</button>		  
	   </td>
	 </tr>	   
  </table>  
</form> 
reactive-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { UserService } from './user-service';
import { User } from './user';

@Component({
   selector: 'app-reactive',
   templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent { 
        isValidFormSubmitted: boolean = null;
	userForm = new FormGroup({
	   uname: new FormControl('', Validators.required),
	   married: new FormControl(false),
	   tc: new FormControl('', Validators.required)
	});
	user = new User();
	constructor(private userService: UserService) {
	}	
        onFormSubmit() {
	   this.isValidFormSubmitted = false;
	   if(this.userForm.invalid){
		  return;	
	   } 	
	   this.isValidFormSubmitted = true;	
	   console.log(this.userForm.valid);
	   this.user.userName = this.userForm.get('uname').value;
	   this.user.isMarried = this.userForm.get('married').value;
	   this.user.isTCAccepted = this.userForm.get('tc').value;
	   this.userService.createUser(this.user);	 
	   this.reset();
	}
	reset() {
	   this.userForm.reset({
		    married: false
	   });	
	}	
	setDefaultValues() {
	   this.userForm.patchValue({uname: 'Krishna', married:true});
	}	
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
                <app-md-checkbox-demo></app-md-checkbox-demo>
		<app-template></app-template>
		<app-reactive></app-reactive>				
             `
})
export class AppComponent { 
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MdCheckboxModule, MdButtonModule, MdInputModule, MdTableModule } from '@angular/material';

import { AppComponent }  from './app.component';
import { MDCheckboxDemoComponent } from './md-checkbox-demo.component';
import { TemplateDrivenFormComponent }  from './template-driven-form.component';
import { ReactiveFormComponent }  from './reactive-form.component';
import { UserService } from './user-service';

@NgModule({
  imports: [     
        BrowserModule,
	BrowserAnimationsModule,
	FormsModule, 
	ReactiveFormsModule,
	MdCheckboxModule,
	MdButtonModule,		
	MdInputModule,
	MdTableModule
  ],
  declarations: [
        AppComponent,
	MDCheckboxDemoComponent,
	TemplateDrivenFormComponent,
	ReactiveFormComponent
  ],
  providers: [
        UserService
  ],
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { } 

Run Application

To run the application, find following steps.
1. Install Angular CLI using the link .
2. Install Angular Material using the link .
3. Download source code using download link given below on this page.
4. Use downloaded src in your angular CLI application.
5. Run ng serve using command prompt.
6. Now access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Checkbox Example

Reference

Angular Material Checkbox

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us