Let’s face it, we work with forms on a day-to-day basis, and with Angular, what better way to work with forms than Angular material mat-form-field?
However, at times, we face the infamous error:
mat-form-field must contain a MatFormFieldControl
Well, not to worry, let us fix Angular material mat-form-field error in a few lines of code!
Well, this change will need two parts, the first is the HTML and the second is the module part, or in our case, we are working with Angular standalone components.
HTML
Before
<mat-form-field>
<input type="text" matInput />
</mat-form-field>
After
<mat-form-field>
<input type="text" matInput />
</mat-form-field>
Component
Before
@Component({
selector: 'app-mat-form-field-error',
standalone: true,
imports: [MatFormFieldModule],
templateUrl: './mat-form-field-error.component.html',
styleUrls: ['./mat-form-field-error.component.scss'],
})
export class MatFormFieldErrorComponent {}
After
@Component({
selector: 'app-mat-form-field-error',
standalone: true,
imports: [MatFormFieldModule, MatInputModule],
templateUrl: './mat-form-field-error.component.html',
styleUrls: ['./mat-form-field-error.component.scss'],
})
export class MatFormFieldErrorComponent {}
So, on the HTML, we are adding matInput, this is what is missing from the HTML input field, and for us to get hold of matInput, we will need to import it in our Angular standalone component as MatInputModule. This will help us get hold of Angular MatFormFieldControl.
This also applies to inputs of different types number, email, and even textarea. Why not give it a go and try this with a textarea?
And with that, we can wrap up this fix for Angular material mat-form-field here, and until the next article, be good!