Angular material导入mat-checkbox时出错

Angular material Error when mat-checkbox is imported

我在使用 Angular Material 时遇到了一些问题,我尝试了很多解决方案,但其中 none 行得通。这就是我想要做的:

我正在使用 Angular Material 和 Reactive Forms 制作 register 表单,在我添加 mat-checkbox 组件之前一切正常。这是我得到的 error :

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

这是我的代码:

HTML :

<mat-form-field>
   <mat-checkbox formControlName="check">
      Check me!
   </mat-checkbox>
</mat-form-field>

组件:

this.registerForm = this.formBuilder.group({
    name: ['', Validators.required ],
    email: ['', Validators.required],
    check: ['', Validators.required ]
});

模块:

import { ReactiveFormsModule } from '@angular/forms';
import { RegisterFormComponent } from './register-form.component';
import { MatCheckboxModule } from '@angular/material';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
 imports: [
    ReactiveFormsModule,
    MatInputModule,
    MatFormFieldModule,
    MatCheckboxModule,
    BrowserAnimationsModule
 ],
 declarations: [
    RegisterFormComponent
 ]
})

export class RegisterFormModule { }

我导入了模块,因此 Angular Material 工作正常,实现了表单控件名称,但我仍然得到相同的 error。我试图在我的 html 中包含 mat-checkbox 而没有 mat-form-field 容器并且它完美无误地工作,但我真的需要使用表单字段,因为我想添加一些 mat-error 组件来显示验证消息。

有人知道我错过了什么吗?

该错误表示表单字段在其中找不到兼容的 material 输入。

不要在 <mat-form-field>.

中使用 <mat-checkbox>

The following Angular Material components are designed to work inside a <mat-form-field>:

  • <input matNativeControl> & <textarea matNativeControl> (version 7 & newer)
  • <select matNativeControl> (version 7 & newer)
  • <input matInput> & <textarea matInput> (version 5 & 6)
  • <mat-select>
  • <mat-chip-list>

来源:Official docs