0

I am try to get the form value using the get method (getter) and then pushing it dynamically to update the form with values. But right now I am dealing with nested array. so I am not able to get the form values.

Bellow is the code to get the formArrays of 0th position.

get detailsControl(): FormArray { return this.dataForm.get(['info_details','0' ,'subinfo']) as FormArray; };

Instead of '0' how I can pass 'i' so that I will get the entire nested formArray ?

1 Answer 1

0

It sounds like you want that getter to return the entire FormArray, which means all you need is this,

return this.dataForm.get('myFormArray') as FormArray;

Or if you want the control at a specific index of the FormArray you can access it like this,

public getControlAtIndex(index: number): AbstractControl {
  let myFormArray: FormArray = myForm.get('myFAControl') as FormArray;
  return myFormArray.at(index);
}

If the control at some index is a FormArray, then querying that index with this function would return the entire nested FormArray. There are some other tricks for grabbing the index value of a FormArray as well. Check out this answer.

But something doesn't sound right about what you are trying to do.. It sounds like you're trying to update the form value with what the form value already is. If you're trying to set the initial value for each control in a FormArray you can do something like this,

for(let i = 0; i < myFormArray.controls.length; i++) {
  myFormArray.at(i).setValue(myVals[i]);
} 

Or,

myFormArray.setValue(["val1", "val2", ...]);
Sign up to request clarification or add additional context in comments.

3 Comments

In get method we have that option to get and push the formArray but is there any way where we can push the value also in the existing form ? My Goal is to create a dynamic form. suppose I clicked on add button than new form will be added to existing form.
Yeah, you can dynamically add controls to the FormArray. Check out this question, stackoverflow.com/questions/59033703/…
And if you want to update the value on a specific control, you can do that too, with the setValue(...) function

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.