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

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

我想使用 Angular Material 日期选择器,但出现此错误。

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

要导入组件和指令等,您需要导入它们的模块,而不是实际的组件和指令。所以你需要导入 MatFormFieldModule 而不是 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 { }