【问题标题】:Patch array of values to Reactive Form将值数组修补到反应形式
【发布时间】:2018-03-23 12:23:42
【问题描述】:

我有一个从服务器返回的 JSON 响应,它是一个包含一系列问题的评估对象。我需要将值传递给我的反应形式。当只有 1 个问题时,此补丁值函数起作用:

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([]),但我仍然不知道如何动态修补这些值。有没有人有任何想法?

【问题讨论】:

  • 为什么要在一个问题中修补一系列问题?这将如何在 HTML 中以图形方式显示?我没有得到你的问题
  • @Med_Ali_Rachid 这是 1 次评估的一系列问题。因此,html 将显示评估名称、类型、状态和描述,但问题将是一个数组。
  • 正如我在您发布的对象中看到的,questions 是一个对象,而不是一个数组,当评估包含多个时,您能否给我一个来自服务器的 JSON 示例问题
  • 评论不允许我发布 json 只是一起运行,但是:description: "Six" name: "Template Six" status: Not Started" templateID: 3 templateQuestions: Array(3) 0{questionID: 6, name: "Check your favorite one", goal: "Any Goal", isAddToOverview: false, isDefaultToLastResponse: null, …} 1{questionID: 3, name: "Question 3", goal: "Any Goal", isAddToOverview: false, isDefaultToLastResponse: null, …} 2 {questionID: 1, name: "Question 1", goal: "Any Goal", isAddToOverview: false, isDefaultToLastResponse: null, …}

标签: json angular typescript angular-reactive-forms


【解决方案1】:

你需要做的是迭代传入的数组,将每个对象作为一个 FormGroup 推送到一个 formArray。所以构建可以有一个空的表单数组:

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

...fb 指的是FormBuilder

当您获取数据时,您对其进行迭代并将表单组推送到该表单数组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
    }))
  })
}

【讨论】:

  • 谢谢!我认为这让我更近了一步。我现在收到此错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。表单数组是否不被视为出于目的或 ngFor 的数组?
  • 是的,它被认为是一个数组。你的迭代看起来如何?它应该类似于*ngFor="let question of caseAssessmentForm.controls.questions.controls"
猜你喜欢
  • 2020-11-07
  • 2021-10-28
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 2019-11-03
  • 2019-04-12
  • 2019-10-26
  • 2022-01-03
相关资源
最近更新 更多