2

I am using Reactive Forms in Angular and have a disabled Form Control that is calculated based on the values of the other fields/Form Controls. How can I update the value of that disabled field as the value of it's dependent fields changes. The calculation is working but I need it to subscribe to the other field's changes. My function that creates the FormGroup looks like this:

createBasket(basket: any) {
    return new FormGroup({
      length: new FormControl(basket.length),
      width: new FormControl(basket.width),
      height: new FormControl(basket.height),
      crossSectArea: new FormControl({value: basket.length * basket.width * basket.height, disabled: true}, Validators.required)
    });
  }

Not sure if this would change the solution, but I am also using FormArray to create an array of the Form Group instances.

1 Answer 1

4

The FormControl API exposes a valueChanges observable which you can subscribe to and then use the setValue method to imperatively set the value of the other form control in the subscribe block:

ngOnInit() {
  this.basketForm = createBasket(basket);
  const length = this.basketForm.get('length');
  const width = this.basketForm.get('width');
  length.valueChanges.subscribe(val => {
    width.setValue(val * 2);
  });
}

Working example: https://stackblitz.com/edit/interdependent-form-controls.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks vincecampanale for the detailed answer. I am using Custom Validator elsewhere, I just felt like there has to be a simpler solution to my issue as I don't need to validate any fields, I just need to update the value (calculation) of a field when the other changes.
I totally misread your question the first time, my bad! Updated my answer so it actually answers your question.
Haha, no worries thanks! My only question is how to implement this within a FormArray?
Happy to help, I'm not sure how to answer your question based on the code you provided. If you want to set the value of a control in an array you can use the setControl on the FormArray. If you want to set the value of the array you can use the setValue method as I showed above. If the group you showed in the question is the member of an array, you can iterate through that array and use the approach I mentioned. It depends on your code and what you're trying to do, but this general combo of valueChanges and setValue will do the trick in any case.
Here's a link to the FormArray API docs for good measure: angular.io/api/forms/FormArray. Does that information help?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.