Ole
Ole

Reputation: 46890

How to use mat-slide-toggle with FormControl?

In this answer it says that we should be able to do something like this:

<mat-slide-toggle [formControlName]="toggleControl">Slide</mat-slide-toggle>

However I'm trying that out in this Stackblitz and it generates the error:

Error in src/app/app.component.html (1:19) Type 'FormControl' is not assignable to type 'string | number'. Type 'FormControl' is not assignable to type 'number'.

Upvotes: 10

Views: 20141

Answers (3)

klebers
klebers

Reputation: 41

Example:

.html

<form class="example-form" #form="ngForm" (ngSubmit)="onFormSubmit()" ngNativeValidate>

      <mat-slide-toggle ngModel name="enableWifi">Enable Wifi</mat-slide-toggle>
      <mat-slide-toggle ngModel name="acceptTerms" required>Accept Terms of Service</mat-slide-toggle>

      <button mat-raised-button type="submit">Save Settings</button>
</form>

.ts

export class SlideToggleFormsExample {
  formGroup: FormGroup;

  constructor(formBuilder: FormBuilder) {
    this.formGroup = formBuilder.group({
      enableWifi: '',
      acceptTerms: ['', Validators.requiredTrue]
    });
  }

  onFormSubmit() {
    alert(JSON.stringify(this.formGroup.value, null, 2));
  }
}

source: https://stackblitz.com/angular/gjjngpabxnlv?file=src%2Fapp%2Fslide-toggle-forms-example.ts

Upvotes: 3

IvanS95
IvanS95

Reputation: 5732

It comes down to the way you are using the FormControl, when you use it inside a FormGroup you need to declare the form controls inside the form group using formControlName, like this:

<form [formGroup]="myForm">
  <input type="text" formControlName="myInput">
</form>

But if you just need a single or simple FormControl you can just declare it like:

<input [formControl]="myInput"/>

This is your case, so just change your directive to [formControl] instead of [formControlName]:

<mat-slide-toggle [formControl]="toggleControl">Slide</mat-slide-toggle>

Upvotes: 12

Patrick
Patrick

Reputation: 103

Try to use formControlName="toggleControl" instead of [formControlName]="toggleControl". The error is gone.

You can also take a look at the documentation here.

Upvotes: 2

Related Questions