Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 418
Kevin192291 Avatar asked May 06 '19 19:05

Kevin192291


People also ask

How do you use a toggle mat button?

By default, mat-button-toggle-group acts like a radio-button group- only one item can be selected. In this mode, the value of the mat-button-toggle-group will reflect the value of the selected button and ngModel is supported. Adding the multiple attribute allows multiple items to be selected (checkbox behavior).

What is matInput?

Matinput is an Angular directive that primarily allows input and text area elements to work with a form field. With this, you can display placeholders perfectly, add custom error messages, a clear button, specify the maximum length of the text or add prefixes and suffixes for a seamless user experience.


Video Answer


3 Answers

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>
like image 120
pcnate Avatar answered Oct 19 '22 20:10

pcnate


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>
like image 20
Ronnie Avatar answered Oct 19 '22 19:10

Ronnie


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>
like image 1
Nathan Avatar answered Oct 19 '22 19:10

Nathan