formArray - 找不到数组数组的路径

formArray - Cannot find path to array of arrays

我的 FormGroup 有这个结构

asyncValidator: null
     controls: Object
       arr: FormArray
       asyncValidator: null
         controls: Array[6]
           0: FormGroup
           asyncValidator: null
           controls: Object
             name: FormControl
             pay: FormControl
             scores: FormArray
             asyncValidator: null
              controls: Array[3]
                0: FormControl
                   ...
                   value: 1
                   ...
                1: FormControl
                2: FormControl
                errors: null
                   ...

访问 FormControl 和“scores”FormArray 值的正确html语法是什么

我尝试了以下 html 的多种组合,但都没有成功

{{myForm.value | json}}
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div formArrayName="arr" *ngFor="let a of myForm.get('arr').controls; let i = index">
    <div [formGroupName]="i" style="margin-bottom: 10px;">
      <input type="text" name="name" formControlName="name">
      <label for="pay">Pay:</label>
      <input type="text" name="pay" formControlName="pay">
      <div [formArrayName]="scores">
      <div  *ngFor="let _ of scores.controls; let g = index"> 
      <input type="text"  [formControlName]="g">
    </div></div></div></div>
  <button type="submit">Submit</button>
</form>

姓名和薪水已正确返回。

报告的错误是

ERROR
Error: Cannot find control with path: 'arr -> 0 -> '
ERROR
Error: Cannot read properties of undefined (reading 'controls')

您可以尝试以下 html:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div formArrayName="arr" *ngFor="let a of arr.controls; let i = index">  <!-- arr getter is called -->
    <div [formGroupName]="i" style="margin-bottom: 10px;">
      <input type="text" name="name" formControlName="name">
      <label for="pay">Pay:</label>
      <input type="text" name="pay" formControlName="pay">
      <div formArrayName="scores"> <!-- Property binding is not required  -->
      <div  *ngFor="let _ of scores(i).controls; let g = index"> <!-- inner FormArray is retrieved based on index -->
      <input type="text"  [formControlName]="g">
    </div></div></div></div>
  <button type="submit">Submit</button>
</form>

并定义适当的 getter 和获取 FormArray 的方法:

// returns the outer FormArray
get arr(): FormArray {
  return this.myForm.get('arr') as FormArray;
}

// returns the inner FormArray based on the index 
scores(index: number): FormArray {
  return this.arr.at(index).get('scores') as FormArray;
}