mat-form-field错误:多个自定义值访问器与表单控件匹配

时间:2019-05-23 20:13:52

标签: javascript angular angular-material angular-material-7

我试图将值从mat-datepicker绑定到窗体控件。当我尝试做类似的事情 this example我看到抛出此错误:

"Uncaught (in promise): Error: More than one custom value accessor matches form control with unspecified name attribute
Error: More than one custom value accessor matches form control with unspecified name attribute"

我也尝试过使用formControlName,但是会引发相同的错误。我在这里做错了什么?

代码:

xhtml

<mat-form-field>
  <input matInput [matDatepicker]="picker1" placeholder="Angular forms" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1></mat-datepicker>
</mat-form-field>

打字稿

  date = new FormControl(new Date());

...并带有formControlName

xhtml

<form-container title="Fake Title">
  <form [formGroup]="form" novalidate="" class="form" (ngSubmit)="onSubmitForm()">
    <mat-form-field>
      <input matInput [matDatepicker]="picker1" placeholder="Angular forms" formControlName="date">
      <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
      <mat-datepicker #picker1></mat-datepicker>
    </mat-form-field>

打字稿

  buildForm(): FormGroup {

    return this.formBuilder.group({
      date: [new Date()]
    });

2 个答案:

答案 0 :(得分:0)

尝试为您的输入提供名称属性

像这样更改代码:

<mat-form-field>
  <input matInput #input [matDatepicker]="picker1" placeholder="Angular forms" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1></mat-datepicker>
</mat-form-field>

答案 1 :(得分:0)

我无法使用您提供的Stackblitz重现该错误。但是我确实对其进行了清理,并提供了许多修复程序:

  • <form [formGroup]="form">添加到模板
  • 在组件中声明form: FormGroup;
  • 注入FormBuilder并调用函数以构建表单
  constructor(private formBuilder: FormBuilder) {
    this.form = this.buildForm();
  }
  • 在控件名称中添加Control,即dateControl
  • 使用buildForm()函数通过控件设置表单
  buildForm(): FormGroup {
    return this.formBuilder.group({
      date: this.dateControl,
      serializedDate: this.serializedDateControl
    });
  }

Updated StackBlitz