Angular SUM to fields value

Viewed 58

Kindly check my code where I am wrong. add(+) function is not working for me. instead of adding, it concatenates. ex: 2 + 2 = 22 it should be 2 + 2 = 4

CalculateQty(i){
          let total = this.assetRevaluationForm.get('ItemRec') as FormArray;
          let formGroup = total.controls[i] as FormGroup;
          formGroup
            .get('NewDep')
            .patchValue(formGroup.get ('netBookValue').value + formGroup.get('revaluedAmount').value);   
            
          }
2 Answers

That's because the values are read as strings. So "+" doesn't perform an addition, but a string concatenation instead.

Add type="number" to your input tags.

Alternatively, you could parse the values as numbers, like this Number(...), but this requires extra checks to avoid parsing errors. For example, if your user types a character in your field, this will result in a NaN value.

the value stored in the formControl is a string, so it adds it like a string. wrap it with Number :

Number(formGroup.get ('netBookValue').value) + Number(formGroup.get('revaluedAmount').value)

if you'r using angular 14 you can add type to your formControl like this:

new FormControl<number>(0)

so in this case you can use mathematics operators on the value with no casting...

good luck :)

Related