Search code examples
angularangular6angular-reactive-formsangular-formsangular4-forms

Getting Value From Nested Table FormArray In Reactive Forms


I had a trouble finding the amount based from quantity * price. The problem is because each row has sub rows How will i able to get the amount from the quantity and the price? Here's my code below.

Here is also the link to my demo code 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;
      });
    });
  }

Solution

  • The problem here is that you're trying to cast FormControl to number while you need to get value from control and then cast to number:

    So instead of:

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

    you should be doing something like:

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

    Forked Stackblitz