Home > Software design >  Calculate Totals Of FormArray Angular
Calculate Totals Of FormArray Angular

Time:10-04

I wanted to multiply the num1 to num2 and put it to the subtotal. and if I push another row it will also multiply the num1 to num2

Lastly I want to add all the subtotal and put it in total how to achieve that?

here is my stackblitz that i created

https://stackblitz.com/edit/mat-dialog-example-scrwra

CodePudding user response:

One way of doing is add change event on input element then pass index as argument

  <td>
      <input
        type="number"
        (change)="onChange(i)"
        formControlName="num1"
        style="width:70px;2px"
      />
    </td>
    <td>
      <input
        type="number"
        (change)="onChange(i)"
        formControlName="num2"
        style="width:70px;2px"
      />
    </td>
    <td>
      <input
        type="number"
        (change)="onChange(i)"
        formControlName="subtotal"
        style="width:70px;2px"
      />
    </td>

Then finally based on index you can access num1 and num2 control and calculate total

 onChange(index:number){
    const total = (this.Info.at(index).get('num1').value || 0)  
    (this.Info.at(index).get('num2').value || 0);
    this.Info.at(index).get('subtotal').setValue(total);
  }

Forked Example

CodePudding user response:

You can do this by using angular form value changes like this:

this.Info.valueChanges.subscribe((datas: Array<any>) => {
      var total = 0;
      datas.forEach((data, index) => {
        const sub = data.num1 * data.num2;
        total = total   sub;
        this.Info.controls[index]
          .get('subtotal')
          .patchValue(sub, { emitEvent: false });
      });
      this.fg.get('total').patchValue(total);
    });

https://stackblitz.com/edit/mat-dialog-example-qw3kpz?file=app/app.component.ts,app/app.component.html

  • Related