2
votes

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

1 Answers

4
votes

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.