veroneseComS
veroneseComS

Reputation: 768

How to get a sum elements of a keyup in angular?

I have "N" inputs in a formgroup that i need to get the sum:

<input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao">

My Typescript:

sum(value){
    let sum;
    if(sum == null){
      sum = 0;
    }
    sum =  +Number(value.key);
}

When i press "22", i get just:

2.

I already try:

sum += parseFloat(valor.key);

But i get the same response

How can i do this?

I need something like this, but in angular/typescript:

http://jsfiddle.net/35At5/

Upvotes: 0

Views: 1155

Answers (2)

Sunil
Sunil

Reputation: 11243

Your current Implementation can handle only one control only however you need to sum up from all dynamic generated controls.

Follow the steps

1. In ts file

Create a object which can holds all the control model.

public controls = {};

2. in html

<input [(ngModel)]="controls[i]" (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao">

ngModel will create the property inside the controls object

3. Final

Finally need to get the values of controls object and sum it up.

 let sum = 0;
 Object.keys(this.controls).map(key => {
   sum +=  +this.controls[key];
 });
 console.log(sum);

That's all !

Upvotes: 1

Mike Tung
Mike Tung

Reputation: 4821

Your keyup event only preserves what you entered at keyup, it has no knowledge of previous key up events. You can however get the inputs of each of your form controls by calling the formControl.value() method and summing up your form controls.

Upvotes: 0

Related Questions