Reputation: 768
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:
Upvotes: 0
Views: 1155
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
Create a object which can holds all the control model.
public controls = {};
<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
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
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