Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MatSlideToggleChange of mat-slide-toggle in Angular Material

I'm trying to use a switch in a form to toggle the appearance of one of two dropdown menus in the same form. I believe that this means I want to use the MatSlideToggleChange class emitted by a MatSlide toggle. Unfortunately, the documentation doesn't provide an example of how to use the MatSlideToggleChange class with a MatSlide.

Has anybody used the MatSlide in this way?

like image 839
Atticus29 Avatar asked Apr 30 '18 05:04

Atticus29


People also ask

How do you find the value of the mat slide 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.

How do you change the mat color on a slide toggle?

The color of a <mat-slide-toggle> can be changed by using the color property. By default, slide-toggles use the theme's accent color. This can be changed to 'primary' or 'warn' .

How do you label both sides of a mat slide toggle?

Add class mat-slide-toggle-content (which is defined by angular material and applied to the label) to your secondary label and also append following three CSS rules to the label. Save this answer.


2 Answers

you can use output change property to toogle its change value

<mat-slide-toggle
   [(ngModel)]="checked"
   class="example-margin"
   [color]="color"
   (change)="changed()">
     Slide me! {{checked}}
</mat-slide-toggle>

component

color = 'accent';
checked = false;

  changed(){
    console.log(this.checked)
  }

demo stackblitz

like image 114
Abinesh Joyel Avatar answered Sep 20 '22 17:09

Abinesh Joyel


MatSlideToggleChange has two fields:

source: MatSlideToggle
checked: boolean

In .html file

<mat-slide-toggle
   (change)="onChange($event)">
</mat-slide-toggle>

In .ts file

onChange($event: MatSlideToggleChange) {
    console.log($event);
}

You would get output like this in the console:

MatSlideToggleChange {source: MatSlideToggle, checked: false}

If you were thinking about using the (click) event instead of the (change) event, I would recommend to use the (change) event instead for better mobile support when the user drags the mat-slide-toggle. You basically just inspect the value of the $event which is a MatSlideToggleChange.

like image 38
Nick Gallimore Avatar answered Sep 21 '22 17:09

Nick Gallimore