Kevin192291
Kevin192291

Reputation: 2097

angular material mat-slide-toggle inside a mat-form-field

If I have a mat-slide-toggle inside a mat-form-field I get the error:

Error: mat-form-field must contain a MatFormFieldControl

I want my mat-slide-toggle inside my mat-form-field so i can get the styling. Any ideas why i get this error? Is a mat-slide-toggle not a mat-form-field???

Here is an example of what I currently have:

<mat-form-field fxFlexFill *ngSwitchCase="'mat-slide-toggle'">
    <mat-slide-toggle>{{el.text}}</mat-slide-toggle>
</mat-form-field>

Upvotes: 27

Views: 25881

Answers (5)

pcnate
pcnate

Reputation: 1774

I present two slightly different hacks with no underline based upon multiple answers

Label above with extended clickable white space, uses css

enter image description here

<mat-form-field floatLabel="always" appearance="none">
  <mat-label>Override Speed</mat-label>
  <mat-slide-toggle [(ngModel)]="Override"><span class="text-invisible">Override Speed</span></mat-slide-toggle>
  <textarea matInput hidden></textarea>
</mat-form-field>
.text-invisible {
  opacity: 0;
}

Label to the right, no css

enter image description here

<mat-form-field floatLabel="always" appearance="none">
  <mat-slide-toggle [(ngModel)]="Override">Override Speed</mat-slide-toggle>
  <textarea matInput hidden></textarea>
</mat-form-field>

Upvotes: 28

Nathan
Nathan

Reputation: 371

Try adding a hidden input field

<mat-form-field>
  <mat-slide-toggle class="example-margin" [color]="color" [checked]="checked"
    [disabled]="disabled">
    Cumulative
  </mat-slide-toggle>
  <input matInput #value hidden />
</mat-form-field>

Upvotes: 2

Ronnie
Ronnie

Reputation: 8107

You can, however, put a hidden text field inside the mat-form-field to satisfy the requirement and, if necessary, bind all the values together if what you want is to get the same look as the other fields.

<mat-form-field floatLabel="always">
        <mat-label>Label</mat-label>
        <mat-slide-toggle>Raw</mat-slide-toggle>
        <textarea matInput hidden></textarea>
    </mat-form-field>

Upvotes: 8

Francesco
Francesco

Reputation: 435

According to official documentation you can't do this (link).

The following Angular Material components are designed to work inside a <mat-form-field>:

  • <input matNativeControl> & <textarea matNativeControl>
  • <select matNativeControl>
  • <mat-select>
  • <mat-chip-list>

Upvotes: 3

aidan22
aidan22

Reputation: 79

Unfortunately Mat-Form-Fields do not work/function when a mat-slide toggle is inside of them. I had to find this out the hard way myself.

Try this instead:

<div fxFlexFill *ngSwitchCase="'mat-slide-toggle'">
    <mat-slide-toggle>{{el.text}}</mat-slide-toggle>
</div>

Upvotes: -2

Related Questions