问题描述
我有一个来自服务器的 JSON 响应,它是一个带有一系列问题的评估对象.我需要将值传递到我的反应形式.当只有 1 个问题时,此补丁值函数正在工作:
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
}
});
问题是,一旦有多个问题返回,我就无法将该值修补为数组.我试过使用问题:this.FormBuiler.array([]),但我仍然无法弄清楚如何动态修补这些值.有没有人有任何想法?
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?
推荐答案
你需要做的是迭代传入的数组,将每个对象作为一个 FormGroup 推送到一个 formArray.所以构建可能有一个空的表单数组:
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([])
})
...其中 fb
指的是 FormBuilder
.
...where fb
is referring to FormBuilder
.
当您获得数据时,您对其进行迭代并将表单组推送到该表单数组questions
,因此:
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
}))
})
}
这篇关于将值数组修补为响应式表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!