Search code examples
angularangular-reactive-formspatchvalue

How Do I Edit a Nested Form Array using PatchValue?


I have a service that calls an API to populate a select dropdown. When I select an option my OnChange method retrieves data from another service that is being called. that data is then displayed on the UI. The data displays fine, it's that if I want to change something the fields don't get updated. Right now I'm using a push control inside of a forEach to get the data.

const infoTemp = this.tempInfo?.customFields?.textCustomFields;
    infoTemp.forEach((res) => {
      this.customNameFormArr.push(
        this.fb.group({
          name: [res.name],
          value: [res.value],
        })
      );
    });

I'm pretty sure that I have to use patchValue for me to be able to edit the fields. I've tried this piece of code but it doesn't seem to work. Any ideas?

    this.envelopeRequest.controls.newRequest.patchValue({
      customFields: {
        textFields: [
          {
            name: res.name,
            value: res.value
          }
        ]

        }
      })

Here is a link to my StackBlitz demo. Thanks.Demo


Solution

  • In your HTML, you are binding the value with the value attribute.

    <input type="text" value="{{ t.value }}" />
    

    Instead, you need to apply the formControlName attribute to utilize the Reactive Form (way), so it will reflect the value.

    <input type="text" formControlName="value" />
    

    For the second issue, I noticed that when changing the option, the FormArray(s) will retain the value from the previous (selected) option. You are not doing right in resetting/clearing the items in the FormArray(s) before binding with the value for the newly selected option.

    this.customNameFormArr.clear();
    this.customTextFormArr.clear();
    

    Demo @ StackBlitz