首页 > 解决方案 > 导入 mat-checkbox 时出现角度材料错误

问题描述

我在使用 Angular Material 时遇到了一些问题,我尝试了很多解决方案,但都没有奏效。这就是我想要做的:

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

ERROR 错误:mat-form-field 必须包含 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. 我试图在没有 mat-form-field 容器的情况下将其包含mat-checkbox在我的html中,并且它可以完美地工作而没有错误,但我确实需要使用表单字段,因为我想添加一些 mat-error 组件来显示验证消息。

有谁知道我错过了什么?

标签: angularangular-materialangular-reactive-forms

解决方案


该错误意味着表单字段在其中找不到兼容的材料输入。

不要<mat-checkbox>在里面使用<mat-form-field>

以下 Angular Material 组件设计用于在 内部工作<mat-form-field>

  • <input matNativeControl>& <textarea matNativeControl>(第 7 版及更高版本)
  • <select matNativeControl>(第 7 版及更高版本)
  • <input matInput>& <textarea matInput>(版本 5 和 6)
  • <mat-select>
  • <mat-chip-list>

来源:官方文档


推荐阅读