Home > Enterprise >  Angular RxJS Subscription Reference Value
Angular RxJS Subscription Reference Value

Time:03-18

Update: Previously the question didn't clearly explain that the FormGroup object is part of a FormArray.


I am listening to value changes of a FormGroup object which is part of a FormArray, however the passed value seem to be just a value that's not referencing to the original FormGroup object.

formArrayObject.controls.forEach(formGroupObject => {
    formGroupObject
        .valueChanges
        .pipe(takeUntil(this.someUnsubscriber$))
        .subscribe(updatedFormGroupObject => {

            // this doesn't update formGroupObject
            updatedFormGroupObject.anotherProperty = true;
    });
}

How to update another properties of the updated formGroupObject inside the subscription callback?

The problem is not knowing which formGroupObject that was updated, therefore not knowing which formGroupObject to update.

I wish updatedFormGroupObject would return a reference to the updated object, but it didn't.

CodePudding user response:

AbstractControl won't update itself after changing properties coming from valueChanges.

You'll need to update the form value yourself:

formGroupObject.patchValue({
   anotherProperty: true,
});

... or maybe you want to use setValue() but in this case it should be the same:

formGroupObject.setValue({
   ...updatedFormGroupObject,
   anotherProperty: true,
});
  • Related