Angular Material - Slide Toggle



The <mat-slide-toggle>, an Angular Directive, is used as a on/off switch with material design styling and animation capabilities.

In this chapter, we will showcase the configuration required to draw a slide toggle control using Angular Material.

Create Angular Application

Follow the following steps to update the Angular application we created in Angular Material - First Application chapter −

Step Description
1 Create a project with a name material-app as explained in the Angular Material - First Application chapter.
2 Modify app.ts, app.css and app.html as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

app.ts

Following is the content of the modified app.ts.

import { Component, signal } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';

@Component({
   selector: 'app-root',
   imports: [
      FormsModule,
      MatFormFieldModule,
      MatSlideToggleModule, 
      MatCheckboxModule,
      ReactiveFormsModule,
   ],
   templateUrl: './app.html',
   styleUrl: './app.css'
})
export class App {
   protected readonly title = signal('material-app');
   disabled = false;
   checked = false;
}

app.html

Following is the content of the modified HTML host file app.html.

<mat-slide-toggle
   class = "tp-margin"         
   [checked] = "checked"
   [disabled] = "disabled">
   Slide!
</mat-slide-toggle>
<section class = "tp-section">
   <mat-checkbox class = "tp-margin" [(ngModel)] = "checked">Checked</mat-checkbox>
   <mat-checkbox class = "tp-margin" [(ngModel)] = "disabled">Disabled</mat-checkbox>
</section>

app.css

Following is the content of the modified CSS file app.css.

.tp-section {
   display: flex;
   align-content: center;
   align-items: center;
   height: 60px;
}
.tp-margin {
   margin: 30px;
}

Result

Verify the result.

Slide Toggle

Details

  • As first, we've created two check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to handle the slide toggle.

  • Then, we've created the slide toggle and showcased its various attributes bound with variables in .ts file.

Advertisements