Patch array of values to Reactive Form

2019-06-09 10:35发布

I have a JSON response coming back from the server that is an assessment object with an array of questions. I need to path the values to my reactive form. This patch value function is working when there is only 1 question:

this.caseAssessmentForm.patchValue({
  ID: assessment.templateID,
  name: assessment.name,
  type: assessment.typeName,
  status: "Not Started",
  description: assessment.description,
  questions: {
    questionScore: '',
    questionAnswer: '',
    questionGoal: assessment.templateQuestions[0].goal,
    questionName: assessment.templateQuestions[0].name
  }
});

The problem is that once there are multiple questions returning, I can't patch the value as an array. I've tried using questions: this.FormBuiler.array([]), but I still can't figure out how to dynamically patch the values. Does anyone have any ideas?

1条回答
劫难
2楼-- · 2019-06-09 11:10

What you need to do is to iterate the incoming array, push each object as a FormGroup to an formArray. So the build could have an empty form array:

this.caseAssessmentForm = this.fb.group({
  // more fields here...
  questions: this.fb.array([])
})

...where fb is referring to FormBuilder.

When you get your data, you iterate it and push formgroups to that formarray questions, so:

...
this.caseAssessmentForm.patchValue({
  ID: assessment.templateID,
  name: assessment.name,
  type: assessment.typeName,
  status: "Not Started",
  description: assessment.description,
});
this.patchFormArray(); // call this to populate formarray!
...

patchFormArray() {
  let ctrl = <FormArray>this.caseAssessmentForm.controls.questions;
  this.assesment.templateQuestions.forEach(question => {
    ctrl.push(this.fb.group({
      questionScore: '',
      questionAnswer: '',
      questionGoal: question.goal,
      questionName: question.name
    }))
  })
}
查看更多
登录 后发表回答