Angular FormArray 或 FormGroup - 带有额外数据

use*_*412 5 dynamic-forms angular angular-reactive-forms formarray formgroups

我有一个动态创建的表,它显示的数据如下:

<table>
  <tr *ngFor="let product of products">
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.value}}</td>
    <!-- BELOW IS WHERE A NEW VALUE WILL BE ENTERED -->
    <td><input type="text" value=""></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我读到处理这个问题的适当方法是使用 FormsArray。但我也读到,使用 FormsArray 的正确方法是获取其控件数组:

<table>
  <tr *ngFor="let product of this.form.get('productCollection').controls; let i = index;"
     [formGroupName]="i">
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.value}}</td>
    <!-- BELOW IS WHERE A NEW VALUE WILL BE ENTERED -->
    <td><input type="text" formControlName="name"></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

问题是我无权访问此处的描述值。我还没有找到一种方法将其作为元数据传递给控件,​​以便我可以显示它。

那么问题是,对于这样的事情,哪种方法是正确的?是FormArray吗?它是一个 FormGroup 中的一组 FormControl 吗?或者每个表单控件都需要单独存在吗?我愿意接受有关如何开展这项工作的建议。

use*_*412 0

我想我可能已经找到答案了。关键可能是不要执行 FormArray,而是执行 FormGroup 中的 FormControls 数组。这样,我可以继续使用该列表及其所有数据,然后添加基于 FormGroup 的字段。所以,最终结果将是:

<table>
  <tr *ngFor="let product of products">
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.value}}</td>
    <!-- BELOW IS WHERE A NEW VALUE WILL BE ENTERED -->
    <td>
      <div formGroupName="productCollection">
        <input type="text" formControlName="name">
      </div>
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

如果我错了或者有人有更好的方法,请务必展示并让我知道!