Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically update form values in a FormArray using valueChanges

I know that we can use valueChanges on a FormArray and view the changes as it is being typed. My question is straight forward: how do I perform the array.at(i).patchValue in valueChanges? I would need to know the index of the row where I am keying the value and update FormControls. What I would like to achieve is for e.g. in a calculator, I want to dynamically show the value when I add two numbers without having to click outside of the input field.

ngOnInit() {
  this.form = this.fb.group({
    fdnUnitPrice: [''],
    cap_values: this.fb.array([this.fb.group({
      name: '',
      fdnTotalShare: '', 
      fdnVal: '',
    }
    )])
  })
  this.onValChanges();
}

onValChanges(): void {
  this.capValues.valueChanges.subscribe(val => {
    console.log(val.length)
  })
}

In my code above, what should be the result is in fdnVal, it should show the value when I multiply fdnUnitPrice with fdnTotalShare. The next row will probably have a different value for fdnTotalShare, so fdnVal should be different.

like image 333
mhfour Avatar asked Apr 08 '26 20:04

mhfour


1 Answers

I would not use valueChanges for the formarray, but instead a function which is called on input from the user. As the unit price is also editable, we can use the same function on that. So I would suggest the following:

in template:

<input type="number" formControlName="fdnTotalShare" (input)="calculate(cap)"/>

where cap comes from: *ngFor="let cap of capValues.controls;">

and the function:

calculate(cap) {
  cap.get('fdnVal').setValue(
    this.form.get('fdnUnitPrice').value * cap.get('fdnTotalShare').value 
  )
}

Then we would actually listen to valueChanges of the unit price form control, where we then iterate the formarray, and for each formgroup call the calculate function:

onValChanges(): void {
  this.form.get('fdnUnitPrice').valueChanges.subscribe((val) => {
    this.capValues.controls.forEach(cap => {
      this.calculate(cap);
    })
  })
}

DEMO: STACKBLITZ

PS: Remember to unsubscribe to valuChanges when component is destroyed!

like image 103
AT82 Avatar answered Apr 11 '26 20:04

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!