如何以angular2反应形式迭代/显示表单数组?

时间:2018-03-07 17:13:07

标签: html angular forms typescript reactive

如何在我的EditForm中填充此JSON。我有EditForm,我想在Products中显示我的数据,我的Ws给我这个JSON。我在产品外的数据我可以用html显示。有什么问题?

这是我的Json

{
   "StatusCode": 0,
"StatusMessage": "OK",
"StatusDescription": [
    {
        "Products": [
            {
                "p_product_id": "11E8218A54B30C89AE8800FF76874A59",
                "p_product_type_id": "11E7FC041F467AD4B09D00FF76874A59",
                "p_line_num": 233,
                "p_description": "test",
                "p_quantity": 4,
                "p_unit_price": 50,
                "p_subtotal": 120,
                "p_contract_filename": "567897"
            }
        ],
        "sale_item_id": "11E8219D916A69F6AE8800FF76874A59",
        "sale_id": "11E8218B9BA4F278AE8800FF76874A59",
        "client_id": "11E8218A57B28B0AAE8800FF76874A59",
        "salesman_id": "31000000000000000000000000000000",
        "sale_date": "2018-03-06T22:09:43.000Z",
        "notes": "testing",
        "subtotal": 80,
        "total": 50,
        "invoice_number": "28282",
        "invoice_date": "2018-03-06T21:57:41.000Z",
        "amount_paid": 32,
        "lastmoduserid": "31000000000000000000000000000000",
        "lasttodtttm": "2018-03-06T22:09:43.000Z"
    }
]

}

我的代码:

 this.sale.products.forEach(x => {
              (this.editSaleForm.get('products') as FormArray).push(new FormControl(x.products))
            })

html代码:

 <tr class="group" style="cursor: pointer" *ngFor="let sale of editSaleForm.get('products').value; let i = index">
    <td >{{p_product_type_id}}</td>
    <td>{{p_product_id}}</td>
    <td>{{p_unit_price}}</td>
    <td>{{p_quantity}} </td>
  </tr>

1 个答案:

答案 0 :(得分:0)

您必须像{{sale.p_product_type_id}}

那样访问它们
<tr class="group" style="cursor: pointer" *ngFor="let sale of editSaleForm.get('products').value; let i = index">
    <td >{{sale.p_product_type_id}}</td>
    <td>{{sale.p_product_id}}</td>
    <td>{{sale.p_unit_price}}</td>
    <td>{{sale.p_quantity}} </td>
  </tr>

您应该使用FormGroup的数组。并使代码类似于:

this.sale.products.forEach(product => {
    (this.editSaleForm.get('products') as FormArray).push(this.createFormGroupForPoduct(product))
})

createFormGroupForProduct(product: Product): FormGroup {
    return new FormGroup({
       p_line_num: new FormControl(product.p_line_num),
       p_description: new FormControl(product.p_description, [Validators.required]),
       ......
    })
}

这样您就可以将FormArray的值作为产品数组Product[]

获得

我不知道您的代码中是否还有其他问题。