找不到路径为 'myFormArray -> [index] -> myProperty 的控件

Cannot find control with path 'myFormArray -> [index] -> myProperty

我正在尝试使用 Angular ReactiveForms 生成动态表单。 目前我收到错误 Cannot find control with path 'myFormArray -> [index] -> myProperty。我已经检查了在互联网上找到的一些答案,但没有成功。这是我的代码:

HTML:

<form [formGroup]="myForm">
    <div formArrayName="myFormArray" *ngFor="let ctrl of foo.controls; let i=index">
        <div [formGroupName]="i">
            <input matInput type="text" formControlName="myProperty">
        </div>
    </div>
</form>

TS:

export class MyClass implements OnChanges {

  @Input() myData: any;

  myForm: FormGroup;

  get foo(): FormArray{
    return <FormArray>this.myForm.get('myFormArray');
  }

  constructor(private fb: FormBuilder) { }

  ngOnChanges() {
    if (!this.myForm) {
      this.myForm = this.fb.group({
        myFormArray: this.fb.array([this.buildMyFormArray()])
      });
    }

    this.myForm.setControl('myFormArray', this.fb.array(myData || []));
  }

  buildMyFormArray(): FormGroup {
    return this.fb.group({
      myProperty: ''
    });
  }
}

myData 来自父级作为组件中的输入,它看起来像

myData: [
    { myProperty: 'John Doe' },
    { myProperty: 'Jane Doe' },
    { myProperty: 'Jack Doe' }
]

更改中间索引的数据数组中的每一项发生错误。

你能帮帮我吗? 谢谢

您的 myFormArray 控件应该是 FormGroupFormArray,但您正在创建 FormControlFormArray

所以让我们尝试以下操作:

this.myForm.setControl('myFormArray', 
   this.fb.array((this.myData || []).map((x) => this.fb.group(x))));

Ng-run Example