Home  >  Angular  >  Angular Material

Angular Material Slide Toggle

By Arvind Rai, September 22, 2018
This page will walk through Angular Material slide toggle example. To work with slide toggle we need to import MatSlideToggleModule in application module. Slide toggle is created using MatSlideToggle Directive. The selector of MatSlideToggle is mat-slide-toggle. To create a slide toggle we use <mat-slide-toggle> element. MatSlideToggle provides input properties such as ariaLabel, ariaLabelledby, checked, color, disableRipple, disabled, id, labelPosition, name, required. MatSlideToggle provides output properties such as change, dragChange, toggleChange and methods such as focus() and toggle(). Slide toggle gives either true or false value. Slide toggle value can be changed either by drag or toggle. Here on this page we will create slide toggles with its properties and will fetch its values using formControl, formControlName and ngModel with reactive form and template-driven form.

1. Technologies Used

Find the technologies being used in our example.
1. Angular 6.1.0
2. Angular CLI 6.1.3
3. Angular Material 6.4.7
4. TypeScript 2.7.2
5. Node.js 10.3.0
6. NPM 6.1.0

2. Import MatSlideToggleModule

To work with Angular Material slide toggle, we need to import MatSlideToggleModule in application module.
import { MatSlideToggleModule } from '@angular/material/slide-toggle';

@NgModule({
  imports: [
    ------
    MatSlideToggleModule
  ],
  ------
})
export class AppModule { } 

3. Using MatSlideToggle

MatSlideToggle Directive creates slide toggle. Its selector is mat-slide-toggle. Find the sample code to create a slide toggle.
<mat-slide-toggle>Slide</mat-slide-toggle> 
<mat-slide-toggle> works as on/off control. Slide toggle works same as checkbox except indeterminate state. Checkbox can be in indeterminate state but slide toggle cannot be in indeterminate state. To use slide toggle, our Angular application must load HammerJS.
Find the sample code to use <mat-slide-toggle> with formControl and change event.
<mat-slide-toggle [formControl]="autoRenew" (change)="onChange()">Auto-Renew</mat-slide-toggle> 
Find the TS file code.
autoRenew = new FormControl();
onChange() {
  console.log(this.autoRenew.value);
} 
When toggle is on, it gives true value otherwise false value.
Find the print screen of Angular Material slide toggles.
Angular Material Slide Toggle

Now we will discuss properties and methods of MatSlideToggle Directive.

3.1. checked

checked property decides if slide-toggle element is checked or not. It is declared in MatSlideToggle as following.
@Input()
checked: Boolean 
Suppose we have a variable in TS file as below.
autoRenew = true; 
Find the HTML code to bind checked property with slide toggle.
<mat-slide-toggle [checked]="autoRenew">Auto-Renew</mat-slide-toggle> 

3.2. color

color property assigns theme color palette for the element. The default color is accent. We can change it to primary and warn. color is declared in MatSlideToggle as following.
@Input()
color: ThemePalette 
Find the HTML code to use color with slide toggle.
<mat-slide-toggle color="primary">Auto-Renew</mat-slide-toggle> 
In our example we will import deeppurple-amber.css in styles.css file.

3.3. disableRipple

disableRipple property is used to enable/disable ripple in slide toggle element. It is declared in MatSlideToggle as following.
@Input()
disableRipple: Boolean 
Find the HTML code to use disableRipple.
<mat-slide-toggle disableRipple="true">Auto-Renew</mat-slide-toggle> 

3.4. disabled

disabled property is used to enable/disable slide toggle element. It is declared in MatSlideToggle as following.
@Input()
disabled: boolean 
We can enable/disable slide toggle at run time. Suppose we have a variable in TS file as following.
isDisabled = true; 
Find the HTML code to use it.
<mat-slide-toggle [disabled]="isDisabled">Auto-Renew</mat-slide-toggle> 

3.5. id

id property defines a unique id for slide toggle element. If we have not supplied any value, it will be auto-generated. It is declared in MatSlideToggle as following.
@Input()
id: string 
Find the HTML code to use it.
<mat-slide-toggle id="slide123">Auto-Renew</mat-slide-toggle> 

3.6. labelPosition

labelPosition property decides if label should appear before or after slide toggle. Default value is after. It is declared in MatSlideToggle as following.
@Input()
labelPosition: 'before' | 'after' 
Find the sample code to display label before slide toggle.
<mat-slide-toggle labelPosition="before">Auto-Renew</mat-slide-toggle> 

3.7. name

name property is used to specify a name to slide toggle element. It is declared in MatSlideToggle as following.
@Input()
name: string | null 
Find the HTML code to use name property.
<mat-slide-toggle name="autoRenew">Auto-Renew</mat-slide-toggle> 

3.8. required

required property is used to apply required validation in slide toggle. It is declared in MatSlideToggle as following.
@Input()
required: Boolean 
Find the HTML code to use required property.
<mat-slide-toggle required ngModel #slide="ngModel">Auto-Renew</mat-slide-toggle>
<br/>{{slide.valid}} 

3.9. change

change is an event that is dispatched each time for change in slide toggle value. It is declared in MatSlideToggle as following.
@Output()
change: EventEmitter<MatSlideToggleChange> 
MatSlideToggleChange has following properties.
checked: It is Boolean value that gives same value as checked property of MatSlideToggle.
source: It is the instance of MatSlideToggle of source slide toggle element.

Find the sample code to use change event.
<mat-slide-toggle (change)="onChange($event)">Auto-Renew</mat-slide-toggle> 
Find the TS file code.
onChange(ob: MatSlideToggleChange) {
  console.log(ob.checked);
  let matSlideToggle: MatSlideToggle = ob.source;	
  console.log(matSlideToggle.color);
  console.log(matSlideToggle.required);
} 

3.10. dragChange

dragChange event will be dispatched each time when slide-toggle is dragged greater that 50%. It does not fire on toggle of slide-toggle. It is declared in MatSlideToggle as following.
@Output()
dragChange: EventEmitter<void> 
Find the sample code to use dragChange event.
<mat-slide-toggle [formControl]="enable" (dragChange)="onDragChange($event)">Drag</mat-slide-toggle> 
Find the TS file code.
enable = new FormControl();
onDragChange() {
  console.log(this.enable.value);
} 

3.11. toggleChange

toggleChange is an event that will be dispatched each time a slide toggle is toggled. It will not fire when slide toggle is dragged to change its value. It is declared in MatSlideToggle as following.
@Output()
toggleChange: EventEmitter<void> 
Find the sample code to use toggleChange event.
<mat-slide-toggle [formControl]="activate" (toggleChange)="onToggleChange($event)">Toggle</mat-slide-toggle> 
Find the TS file code.
activate = new FormControl();
onToggleChange() {
  console.log(this.activate.value);
} 

3.12. focus()

focus() method focuses the slide toggle. For the focus() demo we will instantiate MatSlideToggle Directive in TS file.
@ViewChild('slide')
matSlideToggle: MatSlideToggle;

focusTest() {
  this.matSlideToggle.focus();
} 
Find the HTML code.
<mat-slide-toggle #slide>Premium</mat-slide-toggle>
<br/>
<button mat-raised-button (click)="focusTest()">Focus</button> 

3.13. toggle()

toggle() method toggles the checked state of the slide toggle element. For toggle() demo we will instantiate MatSlideToggle Directive in TS file.
@ViewChild('slide')
matSlideToggle: MatSlideToggle;

toggleTest() {
  this.matSlideToggle.toggle();
} 
Find the HTML code.
<mat-slide-toggle #slide>Premium</mat-slide-toggle>
<br/>
<button mat-raised-button (click)="toggleTest()">Toggle</button> 

4. Reactive Form Example using Slide Toggle

Find the complete code to create slide toggle using reactive form.
reactive-form.component.html
<h4>change, dragChange and toggleChange Test</h4>

<mat-slide-toggle [formControl]="autoRenew" (change)="onChange($event)">Change (Drag or Toggle)</mat-slide-toggle>
<br/>
<mat-slide-toggle [formControl]="enable" (dragChange)="onDragChange($event)">Drag</mat-slide-toggle>
<br/>
<mat-slide-toggle [formControl]="activate" (toggleChange)="onToggleChange($event)">Toggle</mat-slide-toggle>

<h4>focus() and toggle() Test</h4>

<mat-slide-toggle labelPosition="before" #slide>Premium</mat-slide-toggle>
<br/><br/>
<button mat-raised-button (click)="focusTest()">Focus</button>
<button mat-raised-button (click)="toggleTest()">Toggle</button>

<h4>Person Reactive Form</h4>
<form [formGroup]="personForm" (ngSubmit)="onFormSubmit()" #psForm="ngForm">
  <div>
    <mat-form-field>
      <input matInput placeholder="Username" formControlName="username">
      <mat-error *ngIf="username.hasError('required')">
        Username is required.
      </mat-error>
    </mat-form-field>  
  </div>
  <div>
    <mat-slide-toggle formControlName="activateAcc">Activate Account</mat-slide-toggle>
    <div *ngIf="activateAcc.hasError('required') && psForm.submitted" class="error">
      Confirm Activate Account.
    </div> 
  </div>  
  <div>
    <mat-slide-toggle formControlName="premiumUser" color="primary">Premium User</mat-slide-toggle>
  </div>  
  <div>
    <mat-slide-toggle formControlName="autoRenewSub" color="warn">Auto-Renew Subscription</mat-slide-toggle>
  </div>  
  <div>   
    <button mat-raised-button>Submit</button>
  </div>  
</form> 
reactive-form.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, Validators, FormBuilder } from '@angular/forms';
import { MatSlideToggle, MatSlideToggleChange } from '@angular/material/slide-toggle';

import { PersonService } from './person.service';

@Component({
  selector: 'app-reactive',
  templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {
  constructor(private formBuilder: FormBuilder,
        private personService: PersonService) {} 
  ngOnInit() {
  } 
  autoRenew = new FormControl();  
  onChange(ob: MatSlideToggleChange) {
    console.log(ob.checked);
    let matSlideToggle: MatSlideToggle = ob.source;
    console.log(matSlideToggle.color);
    console.log(matSlideToggle.required);

    console.log(this.autoRenew.value);
  }
  enable = new FormControl();
  onDragChange() {
    console.log(this.enable.value);
  }  
  activate = new FormControl();
  onToggleChange() {
    console.log(this.activate.value);
  } 
  
  @ViewChild('slide')
  matSlideToggle: MatSlideToggle;

  focusTest() {
    this.matSlideToggle.focus();
  }
  toggleTest() {
    this.matSlideToggle.toggle();
  }
  
  //Create a form
  personForm = this.formBuilder.group({
    username: ['', Validators.required],
    activateAcc: ['', Validators.required],
    premiumUser: false,
    autoRenewSub: true
  });
  get username() {
    return this.personForm.get('username');
  }  
  get activateAcc() {
    return this.personForm.get('activateAcc');
  }  
  onFormSubmit() {
    this.personService.savePerson(this.personForm.value);
  }  
} 
person.ts
export interface Person {
  username: string;
  activateAcc: boolean;  
  premiumUser: boolean;
  autoRenewSub: boolean;
} 
person.service.ts
import { Injectable } from '@angular/core';
import { Person } from './person';

@Injectable({
  providedIn: 'root'
})
export class PersonService {
  savePerson(person: Person) {
     console.log(person);  
  }
} 

5. Template-Driven Form Example using Slide Toggle

Find the complete code to create slide toggle using template-driven form.
template-driven-form.component.html
<h4>Person Template-Driven Form</h4>
<form #personForm="ngForm" (ngSubmit)="onFormSubmit(personForm)">  
  <div>
    <mat-form-field>
      <input matInput placeholder="Username" 
      name="username" 
      required
      ngModel
      #name="ngModel">
      <mat-error *ngIf="name.hasError('required')">
        Username is required.
      </mat-error>
    </mat-form-field>  
  </div>
  <div>
    <mat-slide-toggle name="activateAcc" ngModel required #activateAcc="ngModel">Activate Account</mat-slide-toggle>
    <div *ngIf="activateAcc.hasError('required') && personForm.submitted" class="error">
      Confirm Activate Account.
    </div> 
  </div>  
  <div>
    <mat-slide-toggle name="premiumUser" ngModel color="primary">Premium User</mat-slide-toggle>
  </div>  
  <div>
    <mat-slide-toggle name="autoRenewSub" [ngModel]="true" color="warn">Auto-Renew Subscription</mat-slide-toggle>
  </div>  
  <div>   
    <button mat-raised-button>Submit</button>
  </div>  
</form> 
template-driven-form.component.ts
import { Component, OnInit } from '@angular/core';
import { PersonService } from './person.service';

@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven-form.component.html'
})
export class TemplateDrivenFormComponent implements OnInit {
  constructor(private personService: PersonService) {} 
  ngOnInit() {
  } 
  onFormSubmit(form) {
    this.personService.savePerson(form.value);
  } 
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-reactive></app-reactive>
    <app-template-driven></app-template-driven>
  ` 
})
export class AppComponent {
} 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';

import { AppComponent } from './app.component';
import { ReactiveFormComponent } from './reactive-form.component';
import { TemplateDrivenFormComponent } from './template-driven-form.component';

@NgModule({
  declarations: [
    AppComponent,
    ReactiveFormComponent,
    TemplateDrivenFormComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,    
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatSlideToggleModule
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { } 
styles.css
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';

.error {
   color: red;
} 

6. Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using 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. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Slide Toggle

7. Reference

Angular Material slide-toggle

8. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us