'No value accessor for form control with name' 在使用 ControlContainer 创建可重用的 matInput 组件时

'No value accessor for form control with name' while creating reusable matInput component with ControlContainer

我正在使用 ControlContainer 跟随 this guide 创建可重复使用的表单,成功创建了一个可重复使用的表单组,但是当我尝试使用 matInput 创建可重复使用的表单元素时,遇到 No value accessor错误。这是 my-form-field.ts 文件:

import { Component, Input, OnInit } from '@angular/core';
import {
  ControlContainer,
  FormBuilder, FormControl,
  FormGroup,
  FormGroupDirective,
} from '@angular/forms';

@Component({
  selector: 'my-form-field',
  template: `
    <mat-form-field>
      <mat-label>{{label}}</mat-label>
      <input matInput [formControlName]="formControlName">
    </mat-form-field>
  `,
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
})
export class MyFormFieldComponent implements OnInit {
  @Input() formControlName: string;
  @Input() label: string;
  formGroup: FormGroup;

  constructor(private ctrlContainer: FormGroupDirective, private formBuilder: FormBuilder) {

  }

  ngOnInit(): void {
    this.formGroup = this.ctrlContainer.form;
    const control = new FormControl('');
    this.formGroup.addControl(this.formControlName, control);
  }
}

下面是我的使用方法:

<form [formGroup]='formGroup'>
  <my-form-field label='Test' formControlName='name'></my-form-field>
</form>

在此处重新创建示例: https://stackblitz.com/edit/angular-9-material-reusable-matinput?file=src/app/my-form-field.ts

我的方法可能是错误的,所以对可重用的 matInput 表单组件的建议也可以。

您正在使用 @Input formControlName 的名称,这让 Angular 感到困惑,请使用其他名称,例如controlName

<my-form-field label='Test' controlName='name'></my-form-field>

并在输入中

@Input('controlName') formControlName: string;