1
votes

I have a page with 3 fields where I am calculating a persons BMI. I have three input fields for this: weight, height and bmi, where a user is able to type into the height and the weight input fields, and the BMI is calculated automatically.

I have an ngModel attached to both my height and weight fields, this saves the data correctly in my model that I have created in my component:

<input [(ngModel)]="masterdataModel.weight" name="weight" type="text" 
       class="form-control" id="input05"
       placeholder="75" formControlName="weight">

<input [(ngModel)]="masterdataModel.height" name="height" type="text" 
       class="form-control" id="input04"
       placeholder="185"  formControlName="height">

In the BMI field I do the calculation in the 'value' tag:

<input [(ngModel)]="masterdataModel.bmi"
       value="{{masterdataModel.weight/(masterdataModel.height/100*masterdataModel.height/100) | number: '1.1-1'}}"
       type="text" class="form-control form-control-rounded" id="input06" 
       style="text-align: center;" formControlName="bmi" placeholder="BMI" name="bmi">

Having the formula in the 'value' tag changes the value in the input field, but it doesn't update the ngModel. I have tried adding (ngModelChange) on the field, but it does not get called either.

How can I solve this properly? Any help is very much appreciated. My model in my component looks like this:

this.masterdataModel = {
      date_of_visit: null,
      date_of_birth: null,
      date_of_pbc_diagnosis: null,
      gender: null,
      height: null,
      weight: null,
      bmi: null,
      ama_positive: null
    }
1

1 Answers

0
votes

You should listen to weight and height model change with a function that will perform and update BMI value calculation, so after that in BMI input you font need to use value={{}} anymore and it will update every time a value changes

Example

<input [(ngModel)]="mymodel.height" (ngModelChange)="updateBMI($event)"> <input [(ngModel)]="mymodel.weight" (ngModelChange)="updateBMI($event)"> <input [(ngModel)]="mymodel.BMI"> And in your typescript component

public updateBMI($event){ this.mymodel.BMI = ... }