Binge On Code

Jun 27, 2023

13 readers

Angular Fix MatFormField Must Contain A MatFormFieldControl

Whenever we are using Angular material, mostly Angular mat-form-field, we get the error that mat-form-field must contain a mat-form-field-control, well, let’s fix that.

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!

Solution

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 {}

 

Discussion

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?

Conclusion

And with that, we can wrap up this fix for Angular material mat-form-field here, and until the next article, be good!

God loves you!

Related Articles

A Practical Example To Validate Angular Input Fields With Joi

At times, we want to do a quick and custom validation of Angular inputs. Well, how let’s see how we can validate Angular input fields using Joi.

Jun 21, 2023

Views 15

Have You Tried Angular Switch Yet

Angular 17 shipped with Angular @switch, and this was a game changer, when it comes to simplicity compared to the former ngSwitch directive. In this guide, we will see how easy it is to use this awesome addition to Angular!

Nov 19, 2024

Views 12

How To Disable Angular HTML Elements Programmatically

At times, we need to disable Angular HTML element like buttons, inputs or even material element, let’s see how we can do this in simple examples.

Jun 19, 2023

Views 46

Angular JavaScript React CSS Django Python React Native Next JS State Management Django Rest Framework Unity