Patch array of values to Reactive Form

一世执手 提交于 2019-12-10 12:18:59

问题


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:


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
    }))
  })
}


来源:https://stackoverflow.com/questions/46694787/patch-array-of-values-to-reactive-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!