基于JSON的Angular Reactive Forms中的嵌套FormArray

时间:2018-05-17 22:02:14

标签: angular typescript angular-reactive-forms angular-forms formarray

我的JSON结构如下......

data = {
  groups: [
    {
      name: 'Primary',
      people: [
         {
           name: 'Jordan',
           begCount: 23,
           endCount: 41
         },
         {
           name: 'Mike',
           begCount: 18,
           endCount: 24
         }
      ]
    },
    {
      name: 'Secondary',
      products: [
         {
           name: 'David',
           begCount: 23,
           endCount: 41
         },
         {
           name: 'Greg',
           begCount: 18,
           endCount: 24
         }
      ]
    },
    {
      name: 'Third',
      products: [
         {
           name: 'Josh',
           begCount: 23,
           endCount: 41
         },
      ]
    }
  ]
};

根据API调用,此数据可能具有“人”的不同数量和值。我正在尝试使用FormBuiler,FormGroup和FormArray来创建一个反应形式和补丁来自数据的值,但我很难搞清楚这一点。以下是使用上述返回数据的UI的图像......

enter image description here

我试图创建一个FormGroup的两个实例,每个实例都有一个数组,但我无法使用它。只是寻找关于如何设置它的一些指示...不担心总数,我可以在我正确地嵌套数组后弄明白。

我当前的HTML看起来像这样......

<form [formGroup]="groupForm">
  <table *ngFor="let group of data.groups">
    <thead>
      <th class="group-name">{{group.name}}</span></th>
      <th>Beginning Tally</th>
      <th>Ending Tally</th>
      <th>Total</th>
    </thead>
    <tbody>
      <tr *ngFor="let person of group.people;  let i=index" formArrayName="people" [formGroupName]="i">
        <td><input type="text" formControlName="name"></td>
        <td><input type="number" formControlName="begCount"></td>
        <td><input type="number" formControlName="endCount"></td>
        <td><input type="number" disabled></td>
      </tr>
      <tr class="grand-total">
        <td></td>
        <td></td>
        <td class="total-label grey"><span>Totals</span></td>
        <td class="grey"></td>
        <td></td>
      </tr>
    </tbody>
  </table>
</form>

0 个答案:

没有答案
相关问题