Search code examples
angular8angular-ngmodelchange

Angular 8 update text field in response to another field change


enter image description here

The image above represents a project I'm working on. Of the 3 fields, only purchase price data is manually entered. I use the following markup and TS code to set the Outstanding mortgage field to a percentage of the previously provided figure:

<input type="number" class="form-control" min='0' id="purchaseValueInput" formControlName="purchase_value" (ngModelChange)='setPercentages()'>

...

setPercentages() {
    this.mortgage = this.analysisForm.value.market.purchase_value * 0.75;
}

My challenge is I need to do a similar thing for the mortgage payments field but as a percentage of the outstanding mortgage value. Because that value is not manually provided the ngModelChange strategy is not working.

How can I resolve that last step?

Update

In my setPercentages() function, I have attempted to set a variable for mortgage payments but I get the following error:

The specified value "NaN" cannot be parsed, or is out of range.

I suspect it's because the field is regarded as empty even though visually it has data in it. I used the following code:

setPercentages() {
  this.mortgage = this.analysisForm.value.market.purchase_value * 0.75;

  this.mortgagePayments = (this.analysisForm.value.market.outstanding_mortgage * 0.03) / 12;
}

<input type="number" class="form-control" min='0' id="mortgagePaymentValueInput" formControlName="mortgage_payments" [value]="mortgagePayments">

Solution

  • I was assigning my percentage values to variables and interpolation to assign the variable as the value of my input field. That proved to the the wrong approach.

    What does work is using form patchValue as shown below:

    this.analysisForm.patchValue({
        market: {
            outstanding_mortgage: this.analysisForm.value.market.purchase_value * 0.75,
        }
    });