0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you can also use this.dynamics.at(0).get('value').setValue(result) or even this.Form.get('dynamics.0.value').setValue(result)
You could, I guess it's the old concision vs readability argument.
3

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>

1 Comment

The question was about setting the value from the component, not the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.