Home > other >  Angular SUM to fields value
Angular SUM to fields value

Time:09-12

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);   
            
          }

CodePudding user response:

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, but this requires extra checks to avoid parsing errors.

CodePudding user response:

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