首页 > 解决方案 > Angular FormGroupArray 元素传递给组件

问题描述

我有一个角度形式,其中包含我想传递给子组件的表单组数组。

this.myForm = this.fb.group({
  name: [''],
  email: [''],
  installations: this.fb.array([]),
  ...

我的初始化程序创建数组中的第一项:

get installations(){
  return this.myForm.get('installations') as FormArray;
}

addInstallation(){
  this.installations.push(
    this.fb.group({
      item1: [''],
      item2: ['']
}

我在我的 html 中迭代安装

<mat-expansion-panel *ngFor="let inst of installations.controls; let i = index">
  <mat-expansion-panel-header>
    <mat-panel-title>Installation {{ i + 1 }}</mat-panel-title>
  </mat-expansion-panel-header>
  <app-installation-details [formGroupName]="i"></app-installation-details>
</mat-expansion-panel>

所以我希望我的 app-installation-details 子组件能够单独安装:

public installationDetailsFormGroup: FormGroup;

constructor(private controlContainer: ControlContainer, private fb: FormBuilder) { }

ngOnInit(): void {
  this.installationDetailsFormGroup = <FormGroup>this.controlContainer.control;
}

但控制台总是抱怨:

Cannot find control with name: '0'

如果我更改通过的项目,它会说同样的话:

 <app-installation-details [formGroupName]="inst"></app-installation-details>

错误与

 Cannot find control with name: '[object Object]'

标签: angularformgroups

解决方案


推荐阅读