angular 4 添加网格控件到formGroup

angular 4 add grid controls to formGroup

我有一个网格,其中一列是输入框。我希望所有这些输入框都属于同一个表单组。我怎样才能做到这一点?

我的是这样的:

    <form [formGroup]="pricesFormGroup">

        <table>
            <tbody>
                <tr *ngFor="let product of products">
                    <td>
                        {{product.productName}}
                    </td>

                    <td>
                        <!--This is control I need to add to my formgroup-->
                        <input type="text"
                                [(ngModel)]="product.Price"
                                required>                                   
                    </td>
                </tr>
            </tbody>
        </table>
    </form>

如果你只想拥有那个值,我会做一些准备工作并制作表单组,这样你就可以直接在模板中显示它并完全忽略 products 数组。在此示例中,我将 product.name 设置为 属性 名称,将 product.Price 设置为值:

iterable = []; // store formgroup object keys to be displayed in template
pricesFormGroup: FormGroup;

constructor(private fb: FormBuilder) {
  this.pricesFormGroup = this.fb.group({});
  this.populateForm();
 }

populateForm() {
  this.products.forEach(x => {
    this.pricesFormGroup.addControl(x.productName, new FormControl(x.Price))
  })
  this.iterable = Object.keys(this.pricesFormGroup.value)
}

和模板:

<form [formGroup]="pricesFormGroup">
  <div *ngFor="let pro of iterable">
    <p>{{pro}}</p>
    <input [formControlName]="pro">
  </div>
</form>

这会产生..

{
  myProductName1: myProduct1_price
  // ...
}

请忽略我糟糕的命名约定 :D

DEMO