greenCode
greenCode

Reputation: 117

Angular Material DatePicker -- Error: mat-form-field must contain a MatFormFieldControl

I want add a date picker to select a date range.

App module

MatFormFieldModule,
MatDatepickerModule,
MatInputModule,

Form

<mat-form-field appearance="fill">
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker">
    <input matStartDate placeholder="Start date" #arrival>
    <input matEndDate placeholder="End date" #departure>
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

But I receive the following error:

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

Upvotes: 2

Views: 10038

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24114

The Angular Material docs provide the following error description:

Error: mat-form-field must contain a MatFormFieldControl

This error occurs when you have not added a form field control to your form field. If your form field contains a native <input> or <textarea> element, make sure you've added the matInput directive to it and have imported MatInputModule. Other components that can act as a form field control include <mat-select>, <mat-chip-list>, and any custom form field controls you've created.

The matInput directive needs to be added to the <input> elements.

To select a date range using two date-pickers, place each date-picker within its own mat-form-field. See Angular example Datepicker palette colors

Example

<mat-form-field class="example-full-width" appearance="fill">
  <mat-label>Enter a date range</mat-label>
  <input matInput [matDatepicker]="picker">
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Upvotes: 2

Related Questions