Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initializate a mat-slide-toggle of Material Design in Angular 5?

I can't make the initialization of a mat-slide-toggle in a Reactive Form.

I have something like in the template

<mat-slide-toggle name="X" formControlName="X" color="primary"></mat-slide-toggle>

and in the controller I am doing

X:  new FormControl(true, [
      Validators.required
    ])

I have also tried with 1 or 0 or false instead of true but I didn't get it with a default value selected.

I would appreciate if someone could help me, many thanks.

like image 470
ackuser Avatar asked Jun 13 '18 14:06

ackuser


People also ask

What is mat slide toggle?

MatSlideToggle uses an internal <input type="checkbox"> with role="switch" to provide an accessible experience. This internal checkbox receives focus and is automatically labelled by the text content of the <mat-slide-toggle> element.


1 Answers

IMHO, there's some issue with your code. You should do something like this:

<mat-slide-toggle [formControlName]="X" [checked]="X.value" (click)="X.value =!X.value" color="primary">{{X.value ? 'ON' : 'OFF'}}</mat-slide-toggle>              

And in controller you'll need to assign the formControl so, use = instead of : ie:

 X = new FormControl(true, [
      Validators.required
 ]);
like image 83
BlackBeard Avatar answered Oct 11 '22 23:10

BlackBeard