Encountering the issue: "Error: The mat-form-field must include a MatFormField

Working on an Angular form, attempting to validate a reactive form with Material design template.

Encountering an error when trying to use ngIf condition for validation in the textbox:

Error: ERROR Error: mat-form-field must contain a MatFormFieldControl.

Solutions attempted:

1. Imported MatInputModule in module.ts file

2. Added matInput to input

Despite these efforts, the error persists.

Including code below:

template -:

<form class="example-form" novalidate (ngSubmit)='user_signup(user)'  [formGroup]='user'>

          <div class="row align-items-center">
            <div class="col-md-1">
              <label><img src="assets/imgs/mobile-icon.svg"/></label>
            </div>
            <div class="col-md-11">
              <mat-form-field class="example-full-width" >
                <input matInput type='number' placeholder="Phone Number:"  maxlength="10" name="phone" formControlName="phone" *ngIf="( user.get('phone').hasError('required') || user.get('phone').hasError('minlength') || user.get('phone').hasError('maxlength'))&& user.get('phone').touched" required/>
              </mat-form-field>
              <div>
              <div class="error" *ngIf="user.get('phone').hasError('required') && user.get('phone').touched">
                Phone number Required
              </div>
              <div class="error" *ngIf="user.get('phone').hasError('minlength') && user.get('phone').touched">
                Min 10 digit
              </div>
              <div class="error" *ngIf="user.get('phone').hasError('maxlength') && user.get('phone').touched">
                Max 10 digit
              </div>
              </div>

            </div>
          </div>
</form>

component.ts

 import { Component, OnInit } from '@angular/core';
    import { ServicesService } from '../service/services.service';
    import { FormGroup  , FormControl  , Validators } from '@angular/forms';
    @Component({
      selector: 'app-register',
      templateUrl: './register.component.html',
      styleUrls: ['./register.component.scss']
    })
    export class RegisterComponent implements OnInit {
     user: FormGroup;
 constructor( public restapi:ServicesService) {

        this.user = new FormGroup({
          password: new FormControl('', [Validators.required, Validators.minLength(6)]),
          email: new FormControl('', [Validators.required,Validators.email]),
          phone: new FormControl('', [Validators.required, Validators.minLength(10),Validators.maxLength(10)]),
          });

       }

  ngOnInit() {
  }
}

module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ComponentsComponent } from './components/components.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule }    from '@angular/common/http';


import { MDBBootstrapModule, WavesModule, ButtonsModule, CardsFreeModule } from 'angular-bootstrap-md';
import { MatTabsModule, MatDialogModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatFormFieldModule} from '@angular/material';


/*angular material compoment*/
import { MatInputModule } from '@angular/material/input';
-import {MatButtonModule} from '@angular/material/button';
+import { MatButtonModule } from '@angular/material/button';
import { RouterModule, Routes } from '@angular/router';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatTableModule} from '@angular/material/table';
import {MatSelectModule} from '@angular/material/select';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {MatSliderModule} from '@angular/material/slider';
import {MatBadgeModule} from '@angular/material/badge';

/*component */
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { FleshScreenComponent } from './flesh-screen/flesh-screen.component';


/* Service */
import { ServicesService } from './service/services.service';

@NgModule({
  declarations: [
    AppComponent,
    ComponentsComponent,
    LoginComponent,
    RegisterComponent,
    FleshScreenComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatButtonModule,
    MDBBootstrapModule.forRoot(),
    ReactiveFormsModule ,
    HttpClientModule ,
    MatFormFieldModule

  ],
  schemas: [ NO_ERRORS_SCHEMA ],
  providers: [ServicesService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

I haven't tested it yet, but the reason for this error might be due to using the *ngIf directive on the input element.

What's the Issue?

Specifically, in this portion of your code:

<mat-form-field>

    <input *ngIf="...">

</mat-form-field>

The interpretation by Angular is as follows:

<mat-form-field>

    <ng-template [ngIf]="...">
      <input>
    </ng-template>

</mat-form-field>

This means that the input element isn't a direct content child of mat-form-field, causing an issue.

On further investigation from its source, MatFormField needs to locate your input (with matInput directive applied) through @ContentChild. Hence, you need to include your input element as a content child of mat-form-field.

In summary, make sure to position your input element directly under the mat-form-field element.

Solution

Instead of using *ngIf on the input element, apply it to mat-form-field instead. This way, the input element becomes a content child of mat-form-field, resolving the issue.

<mat-form-field *ngIf="...">
    <input>
</mat-form-field>

Answer №2

Whenever you are using a mat-form-field tag, make sure that the inner input/ select tag includes the matNativeControl attribute.

For example:

<mat-form-field>
    <input matInput matNativeControl placeholder="Enter text">
  </mat-form-field>

Check out the official documentation for more information: Link

Answer №3

It appears that there is a typo error in your code. Please update it to the following:

<mat-form-field class="example-full-width" >
    <input matInput type='number' placeholder="Phone Number:"  maxlength="10" name="phone" formControlName="phone" *ngIf="user.get('phone').hasError('required') || user.get('phone').hasError('minlength') || user.get('phone').hasError('maxlength') && user.get('phone').touched" required/>
</mat-form-field>

Answer №4

When referencing MatFormControl, it denotes the formControl intended to be utilized with the specified form field. If directives are employed incorrectly, it may cause the input element not to render properly, resulting in a required error.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the query parameter before undergoing redirection within Angular version 14

In my Angular application, I am facing a challenge where I need to display a specific message to the user once they click on a link that has been sent to them via email. The link is intended to open a page within the app at the URL: "localhost:8080/?d ...

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

Exploring Iframes within Angular2

import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Greetings, {{name}}!</h1> <iframe src="http://example.com/Home?requestId=+[testRequestId]+" allowfulls ...

Encountered difficulties when attempting to install Angular Universal in my angular13 application

I'm facing some challenges while trying to incorporate @nguniversal/ into my angular 13 application. Are there any experts who can offer assistance? Angular CLI: 13.0.4 Node: 16.13.1 Package Manager: npm 8.1.2 npm ERR! code ERESOLVE npm ERR! ERESO ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

Leveraging the power of Kendo UI for Angular, bind the click event of a kendoButton to a method associated with a variable within

I have a variable called "message" in my component that is of type "any" and contains a method named "actionnowrapper()". When I bind this method to a regular HTML button like so, everything works as expected. <button (click)="message.actionnowrapper( ...

Guide to dynamically configuring ViewEncapsulation for a Web Component

When initializing a component, I am facing an issue with setting up Shadow DOM based on the browser type (since IE does not support Shadow DOM). To handle this, I check if the browser is IE11 and then configure the encapsulation as Emulated for IE and Sha ...

Angular2's customer filter pipe allows for easy sorting and filtering of

Check out the component view below: <h2>Topic listing</h2> <form id="filter"> <label>Filter topics by name:</label> <input type="text" [(ngModel)]="term"> </form> <ul id="topic-listing"> <li *ngFo ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...

Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo .ts import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './a ...

The HTML template remains unchanged unless explicitly triggering detectChanges() with change detection set to onpush

In my Angular component, I am utilizing change detection on push. The component includes an input that gets modified by the component when the route changes. However, I noticed that simply assigning a new reference to the input and making modifications d ...

Steps to activate a function within an angular6 form-related directive

Is there a way to execute a function within a directive when the form is marked as pristine? I want to apply a CSS class to a tab header when the form is pristine. <form [formGroup]="awayForm" (ngSubmit)="onSubmit()" awayConfirm [cancelClicked]="cancel ...

Can projects be published on npm and installed from a specific directory?

Currently working on an Angular library project, I am exploring the possibility of publishing the entire library alongside a pre-built angular application either on gitlab or npm. However, my concern lies in ensuring that when a user installs the library v ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Even after making changes within my Angular and Firebase subscription, my variable remains unchanged

In an attempt to secure my Angular application's routes, I decided to create a canActivate method that would check the user's status. My backend is based on Firebase, and user authentication, login, and sign up functionalities are all handled thr ...

Angular 6's removeAt and trackBy functions are causing issues in updating the formArray and not reflecting the

Within a formGroup, I am adding and deleting elements from a formArray. To keep track of the ids to delete, I am using trackBy. When calling the function delete(i), it successfully removes the correct element from the formArray in the form. However, in th ...

tips for instructing the p-table to sort particular columns by utilizing a subfield

I currently have data structured with nested JSON as follows: users = [ { name: "ABC", age: 11, activity : { date: 11-Aug-2020, title: "some activity", loc: "so ...

Effective strategies for extracting value from asynchronous Angular events that return Promises

When it comes to subscription blocks, extracting the value from my API is possible. var data = null; this._timinServiceProxy.getDateFromNTP().subscribe(result => { data = result; console.log(data); // The expected result }); console.log(data); ...