0

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;
      });
    });
  }
1
  • who downvoted? This is a good question Commented Aug 26, 2018 at 6:27

2 Answers 2

1

Try like this:

If you want to calculate amount based from 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 });
      })
    });
Sign up to request clarification or add additional context in comments.

15 Comments

I'll upvote this but i don't want to load the template with functions. I want functions to be implemented by ts file.
but i am not calling any function from template. have u seen?? it is just formGroup controls.
You are multiplying the quantity and the price in the template. I just want it to be done in the ts file
You can just finish my getAmount function in my ts file. Thanks
You're nearing now. But i want it to be using ValueChanges. Just finish my function and don't change anything in the template. Sorry for that and thank you
|
0

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

5 Comments

why there is || 0?
In case if value of your controls is undefined
Thanks. can i do it too when instantiating the form. In this quantity[0, Validators.required]. Is this the same thing?
If you're sure that the value will never be undefined then you can omit it.
Hi yurzui. Can you help me with this stackoverflow.com/questions/52026735/…. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.