将值数组修补到反应形式 [英] Patch array of values to Reactive Form

查看:55
本文介绍了将值数组修补到反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器返回了一个JSON响应,这是一个带有一系列问题的评估对象.我需要将值传递到我的反应形式.当只有一个问题时,此修补程序值函数将起作用:

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

这篇关于将值数组修补到反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆