If you are using Angular material in your project and if you have any forms in the application then you must be using Angular Material Form Field Component <mat-form-field>
from MatFormFieldModule
And of the common error that we usually get is while working with Angular Material Form Field is: mat-form-field must contain a MatFormFieldControl.
In this article we will see how to fix “mat-form-field must contain a MatFormFieldControl” error.
Table of Contents
What is form field and form field controls?
<mat-form-field>
is a component used to wrap several Angular Material components and apply common Text field styles such as the underline, floating label, and hint messages.
The elements like <input>
or <textarea>
, which are placed inside mat-form-field
acts as form field controls.
Solution: mat-form-field must contain a MatFormFieldControl
This error usually occurs in 4 scenarios when we missed to import module for specific component.
Problem 1: MatInputModule or MatFormFieldModule is not imported in AppModule
import MatInputModule
and MatFormFieldModule
inside module i.e. app.module.ts
so that we can use all the component from that module across the application.
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from "@angular/material/form-field";
//other imports
@NgModule({
imports: [
MatFormFieldModule,
MatInputModule
...
...
]
})
export class AppModule { }
Problem 2: matInput – spellings mistake / forget to add
Make sure that you have added matInput
and it is case-sensitive so check if there’s any spelling mistake or not.
Won’t work
<mat-form-field>
<input type="text" placeholder="Input">
</mat-form-field>
Will Work
<mat-form-field>
<input matinput="" type="text" placeholder="Input">
</mat-form-field>
Problem 3: mat-form-field
control input should not contain *ngIf
Make sure that you don’t have any condition on input
tag that is going to be false in any case because mat-form-field
looks for matInput
inside it. Instead put *ngIf
on mat-form-field
tag.
Won’t work
<mat-form-field>
<input matinput="" *ngif="condition">
</mat-form-field>
Will Work
<mat-form-field>
<input matinput="">
</mat-form-field>
Problem 4: Still compiler giving ERROR
If angular compiler is still giving an error after applying solution of all of the above given problems then you must try with restarting the app using the following command.
ng serve
Conclusion
To fix mat-form-field must contain a MatFormFieldControl
error check if you are missing any of the below steps.
- Import
MatInputModule
andMatFormFieldModule
- Add
matInput
directive to themat-form-field
control. i.e.,input
ortextarea
- Check
matInput
spelling or forgot to add. - Make sure you don’t use
*ngIf
onmat-form-field
control instead use it onmat-form-field
element
Also Read:
- JavaScriptArray Methods
- JavaScript Console Methods
- Angular Material Grid Layout Example
- Angular Material Card Example
- Angular Material List Example
- Tailwind CSS Setup