Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 mat-form-field with mat-select

So, I am having problems using mat-select with mat-form-field . Using mat-form-field with mat-input is not a problem, and I am fairly sure my imports are correct as well, yet I receive the following error when trying to use mat-select:

Error: md-form-field must contain a MdFormFieldControl. Did you forget to add mdInput to the native...

My HTML code is the following:

<mat-form-field class="full-width">
  <mat-select name="sampleType" formControlName="sampleTypeCtrl" 
   placeholder="Sample Type" required>
     <mat-option *ngFor="let sample of samples" [value]="sample.value">
       {{ sample.viewValue }}
     </mat-option>
  </mat-select>
</mat-form-field>

My view module that contains this component and is imported into my main app.module.ts file is the following:

...
import { MatFormFieldModule, MatInputModule, MatSelectModule } from 
   '@angular/material';
...

@NgModule({
  imports: [
    ...
    MatInputModule,
    MatFormFieldModule,
    MatSelectModule,
    ...
  ],
})
export class ViewModule {}

My main app.module.ts file includes both the ViewModule and the NoConflictStyleCompatibilityMode imports and looks like the following:

...
import { ViewModule } from './view/view.module';
import { NoConflictStyleCompatibilityMode } from '@angular/material';
...
@NgModule({
  ...
  imports: [
    ViewModule,
    NoConflictStyleCompatibilityMode
  ],
  ...
})
export class AppModule { }

When I remove the mat-form-field from around the mat-select, the error goes away, but I get inconsistencies with how mat-input (using mat-form-field) and mat-select are styled. I am importing both the MatSelectModule and MatFormFieldModule, yet I get this error. I have also updated my npm for angular material 2 so that it has the latest and greatest, but still nothing. What am I overlooking? I have seen this type of problem addressed in recent stackoverflows, but each solution I have already tried without luck.

mat-select Not Working Properly
mat-form-field must contain a MatFormFieldControl

like image 800
John Stafford Avatar asked Nov 03 '17 21:11

John Stafford


2 Answers

I was facing similar issue and from this issue on github I realized that ngIf must not be on mat-select.

This may help some one:

Make sure you don't have an ngIf on your mat-select.

like image 128
skm Avatar answered Nov 17 '22 19:11

skm


Try to just add matInput attribute to your nested mat-select (as error message suggests):

<mat-form-field>
    <mat-select matInput name="mySelect">
        <mat-option>
            ...
        </mat-option>
    </mat-select>
</mat-form-field>

This construction works for me.

UPD.: Quick plnkr example https://plnkr.co/edit/9Yz6xkcVMCMpRhP3Qse9

like image 25
GreenTeaCake Avatar answered Nov 17 '22 21:11

GreenTeaCake