以反应形式从嵌套表FormArray获取价值

时间:2018-08-26 06:09:09

标签: angular angular6 angular-reactive-forms angular-forms angular4-forms

我很难从数量*价格中找到数量。问题是因为每一行都有子行,我如何从数量和价格中获取金额?这是下面的代码。

这也是我的演示代码PLEASE CLICK THIS

的链接
getAmount(value: FormControl) {
    const control = <FormArray>this.myForm.controls['people'];
    this.total = 0;
    control.controls.forEach((field) => {
      field.get('addresses')['controls'].forEach(element => {
        const col1 = +field.get('price')
        const col2 = +element.get('quantity');
        const sum = col1 * col2;

        // Get Amount
        element.get('amount').patchValue(sum, { emitEvent: false });

        // Get Grand Total
        this.total += sum;
      });
    });
  }

2 个答案:

答案 0 :(得分:2)

尝试这样:

如果您要根据quantity * price

计算金额

WORKING DEMO

<td>
{{ myForm['controls'].people.controls[i].controls.addresses.controls[j].controls.amount.value }}
</td>

 getAmount(value) {
    value.forEach((pdata, i) => {
      pdata.addresses.forEach((data, k) => {
        this.myForm['controls'].people['controls'][i].controls.addresses.controls[k].controls.amount.patchValue((pdata.price * data.quantity), { emitEvent: false });
      })
    });

答案 1 :(得分:0)

这里的问题是,您需要将FormControl转换为数字,而又需要从控件中获取值,然后转换为数字:

所以代替:

const col1 = +field.get('price')
const col2 = +element.get('quantity');

您应该执行以下操作:

const col1 = +(field.get('price').value || 0);
const col2 = +(element.get('quantity').value || 0);

Forked Stackblitz