Home > other >  How to setValue of a particular field in Reactive Forms when its an array of objects?
How to setValue of a particular field in Reactive Forms when its an array of objects?

Time:10-05

I have a Dynamic Field being generated that can be n numbers in length. I would like to set the value of a particular field from the TS.

My Form initializing is like:

this.Form = this.fb.group({
      dynamics: this.fb.array([]),
    });

My Json looks like:

    { "dynamics": 

[ { "field": "Country", "operator": "", "value": "", "value2": "", "andOr": "", "date": "2021-10-04T16:11:57.965Z" }, 

{ "field": "", "operator": "", "value": "", "value2": "", "andOr": "", "date": "2021-10-04T16:19:18.835Z" } ] 

}

I would like to set the value of "value" field from TS.

I tried with this.Form.get('dynamics')[0].get('value').setValue(result); but that did not work.

How can I access the element in the dynamics array and then set the value?

Thanks in advance.

CodePudding user response:

You can easily set the value in html by making use of the index. Use the value tag and set the value in html as described below.

    <div formArrayName="dynamic" *ngFor="let dynamic of dynamics.controls; let i = index;">
   <div class="form-group col-md-2">
      <label>Value</label>
        <!-- Use the value tag, and set the value in your form-->
      <select   [value]="dynamics.at(i).controls.dynamic.value" formControlName="value">
      </select>
   </div>
</div>

CodePudding user response:

For clairity, I would first create a getter:

  get dynamics(): FormArray {
    return this.Form.get('dynamics') as FormArray;
  }

And then you want to use at and patchValue:

this.dynamics.at(0).patchValue({value: result})

With setValue you have to set the values for all of the properties of the form array object. patchValue lets you patch just one or more.

  • Related