1

I'm building a form similar to this:

private _buildForm(): FormGroup {
const _form = new FormGroup({
  title: new FormControl('', [Validators.required]),
  jobs: new FormArray([
    new FormGroup({
      _id: new FormControl(''),
      status: new FormControl('')
      });
    ])
  });
}

When I want to patch the form using the patchValue() method (for example, when the data comes back from the server), the jobs array is only patched for one element. In other words, if the jobs array contains more than one job, only the first job FormGroup is patched. I thought Angular would be smart enough to dynamically add as many FormGroups as required to match. How else can the job FormGroups be patched?

3
  • 1
    You can dynamically add as many FormGroup instances to the FormArray as you like, but in the above code there is only one. You need to add the logic to add controls to a FormArray. Commented Sep 8, 2019 at 12:17
  • please check updated code in the answer. Commented Sep 8, 2019 at 13:22
  • As Will Alexander say, you can use pathValue, the problem is that you need that the formArray has the same length than the data before make the pathValue Commented Sep 9, 2019 at 6:53

1 Answer 1

2

No, you can't patch formArray this way. what you can do pass the formArray value as parameter and insert it in the form one by one.

setUpForm(job: Job) {
  return new FormGroup({
    title: new FormControl(job.title), 
    statuses: new FormArray(job.statuses.map((status) => this.createStatus(status))) 
  });
}
createStatus(statuses: any) {
  return new FormGroup({
    id: new FormControl(statuses.id || ''),
    status: new FormControl(statuses.status || ''),
  })
}  

Live Example: Stackblitz

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

Comments

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.