Angular材料导入mat-checkbox时出错

时间:2018-05-14 15:50:43

标签: angular angular-material angular-reactive-forms

我在使用Angular Material时遇到了一些麻烦,我尝试了很多解决方案,但没有一个能够解决问题。这就是我想要做的事情:

我正在使用具有反应形式的Angular材质来制作register形式,在添加mat-checkbox组件之前一切正常。这是我得到的error

  

错误错误:mat-form-field必须包含MatFormFieldControl。

这是我的代码:

HTML:

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

COMPONENT:

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

MODULE:

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-checkbox包含在我的 html 中,而不使用mat-form-field容器,它完美无缺,但我确实需要使用表单字段,因为我想添加一些mat-error组件来显示验证消息。

有谁知道我错过了什么?

2 个答案:

答案 0 :(得分:13)

错误表示表单字段无法在其中找到兼容的材料输入。

请勿在{{1​​}}内使用<mat-checkbox>

  

以下Angular Material组件设计用于<mat-form-field>

     
      
  • <mat-form-field>&amp; <input matInput>

  •   
  • <textarea matInput>

  •   
  • <mat-select>

  •   

来源:Official docs

答案 1 :(得分:0)

在这种情况下,为什么在与matControl.Name一起使用的mat-radio-group的同一链接中,此示例的角材料站点显示此示例。

<form class="example-container" [formGroup]="options">
    <mat-checkbox formControlName="hideRequired">Hide required marker</mat-checkbox>
    <div>
      <label>Float label: </label>`enter code here`
      <mat-radio-group formControlName="floatLabel">
        <mat-radio-button value="auto">Auto</mat-radio-button>
        <mat-radio-button value="always">Always</mat-radio-button>
        <mat-radio-button value="never">Never</mat-radio-button>
      </mat-radio-group>
    </div>
  </form>