When working with reactive form control, all the form controls within the form tag have their values stored in the form instance. Here is an example:
<form [formGroup]="myForm">
<input type="number" formControlName="value1"/>
<input type="number" formControlName="value2"/>
</form>
To create the form, you can use the form builder class like this:
this.myForm = this.fb.group({
value1: [5, Validators.required],
value2: [2, Validators.required]
});
The form instance myForm
will store the updated values of all the controls in the property myForm.value
. In this case, it will contain { "value1": 2, "value2": 5 }
. To calculate the total, you can use this property object to print the sum like so:
sum = Object.keys(this.myForm.value).reduce((prev, curr) => {
return prev + this.myForm.value[curr]
}, 0);