0

How can i get total sum from dynamic inputs in angular 2, have no idea to implement this. Thanks

enter image description here

//html component
<md-input-container style="width: 80px;">
                <input md-input class="debit" formControlName="debit" [(ngModel)]="debit[i]">
              </md-input-container>
3
  • provide your code pls Commented Feb 24, 2017 at 8:21
  • @ŌkamiXOukarin actually i dont have functionality yet, can u help me the idea about this implementation. Commented Feb 24, 2017 at 8:28
  • i have an example here with sum function jsfiddle.net/g6xp1r52 Commented Feb 24, 2017 at 8:51

2 Answers 2

1

I think you are creating debit text dynamically, and you also using ngModel, so you can do this way

(onChange) = "findSum()" for each input-text of debit and set [(ngModel)]="totalVal" for total input-text in .ts file do this

findSum(){sum= 0;
for( data of debit){total = total + data;}
totlaVal = total;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you are using reactive form control then all the form control that are in the form tag have their value in in the form instance as below

<form [formGroup]="myForm">
            <input type="number" formControlName="value1"/>
            <input type="number" formControlName="value2"/>
</form>

and create the form from the form builder class

this.myForm = this.fb.group({
            value1: [5, Validators.required],
            value2: [2, Validators.required]
});

and your form instance myForm will contain the updated values of all the controls in the property myForm.value and according to this example will contain { "value1": 2, "value2": 5 } where you want total for that just use this property object and print the sum like

sum = Object.keys(this.myForm.value).reduce((prev, curr) => {
  return prev + this.myForm.value[curr]
}, 0);

2 Comments

The inputs are dynamic.
no matters . Your form instance always contains the inputs that are registered with that form

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.