我从服务器返回一个JSON响应,这是一个带有一系列问题的评估对象。我需要将值传递给我的反应形式。当只有一个问题时,此补丁值功能正在运行:
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
}
});
问题在于,一旦返回多个问题,我就无法将该值修补为数组。我尝试过使用问题:this.FormBuiler.array([]),但我仍然无法弄清楚如何动态修补这些值。有没有人有任何想法?
答案 0 :(得分:2)
您需要做的是迭代传入的数组,将每个对象作为FormGroup推送到formArray。所以构建可以有一个空的表单数组:
this.caseAssessmentForm = this.fb.group({
// more fields here...
questions: this.fb.array([])
})
...其中fb
指的是FormBuilder
。
获取数据后,将其迭代并将表单组推送到formarray questions
,以便:
...
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
}))
})
}