Uncaught Error: Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a @NgModule annotation

theasishpradhan picture theasishpradhan · Nov 20, 2018 · Viewed 20k times · Source

I Want to use Angular Material Date picker but I am getting this error.

Uncaught Error: Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a @NgModule annotation.

app.component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

app.module.ts

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

import { AppComponent } from './app.component';
import {MatFormField} from '@angular/material';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MatFormField
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer

G. Tranter picture G. Tranter · Nov 20, 2018

To import components and directives etc, you import their modules, not the actual components and directives. So you need to import MatFormFieldModule instead of MatFormField:

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

import { AppComponent } from './app.component';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MatFormFieldModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }