首页 > 解决方案 > 如何使用嵌套表单数组将服务器响应映射到角度响应式表单

问题描述

我正在使用响应式表单方法在 Angular 中开发反馈表单。服务器的响应具有问题数组,而问题数组又具有答案数组。

这是回应。

value": [
{
"description": "why didn't you turn up"
"answers": [
{
"description": "Unexpected Personal Committment"
},
{
"description": "Unexpected Official Work"
},
{
"description": "Even Not What I Expected"
},
{
"description": "Did Not Receive Further Information About The Event"
},
{
"description": "Incorrectly Registered"
},
{
"description": "Do Not Wish to Disclose"
}
]
}
]

我正在尝试如下构建反应形式。

ngOnInit() {
    this.feedbackForm = this.fb.group({
      questions: this.initQuestion()
    })                     
  }

initQuestion() {
    return this.fb.group({
      description: [],
      answers: this.initAnswer()
    })
  }

  initAnswer() {
    return this.fb.group({
      description: this.fb.array([])
    })
  }

如何将问题和响应映射到我的反应形式。

我尝试如下,但从来没有工作,

get questions(): FormArray {
    return <FormArray>this.feedbackForm.get('questions');
  }

  get answers(): FormArray {
    return <FormArray>this.feedbackForm.get('questions').get('answers');
  }

displayQuestions(questions: Response<Question[]>): void {
    if (this.feedbackForm) {
      this.feedbackForm.reset();
    }
    this.questionsResponse = questions;

   if (this.questionsResponse.value.length > 0) {
      this.feedbackForm.setControl('questions', this.fb.array(this.questionsResponse.value || []));
      this.feedbackForm.setControl('answers', this.fb.array(this.questionsResponse.value.answers || []));
    }           
  }

这是我的模板

<form [formGroup]="feedbackForm" novalidate (ngSubmit)="send()"> 
<div formArray="questions">
  <div [formGroup]="i" *ngFor="let question of feedbackForm.controls.questions.controls; let i=index;">
    <p>{{question.description}}</p>
    <div formArray="answers">
      <div [formGroup]="j" *ngFor="let answer of question.controls.answers.controls; let j=index">
      <label [attr.for]="j">{{answer.description}}</label>
      <input type="radio" [id]="j" [formControlName]="j" value="{{answer.descripiton}}" />
    </div>
    </div>
  </div>
</div>

<input type="submit" value="Send">

我正在尝试显示带有答案的问题,我需要用户为问题选择答案,并且在提交时我需要选择的答案值。

标签: angularnestedangular-reactive-formsformarray

解决方案


你做的有点“颠倒”。正确的方法是遍历数组的每个成员并为其创建控件,转到嵌套数组,为它们创建控件,然后将其推送到问题数组。

SetControl 仅替换现有控件。 https://angular.io/api/forms/FormArray#setcontrol

用这个替换最初的定义。

  feedbackForm:FormGroup = this._fb.group({
    questions:this._fb.array([])
  })

并尝试用这个替换最后一个。

if (this.questionsResponse.value.length > 0) {
    this. questionsResponse.forEach(question => {
    (this.feedbackForm.get('questions') as FormArray).push(this.fb.group({
      description:question.description,
      answers:this.fb.array([...question.answers.map(answer => 
         this.fb.group(answer))])
     }))
    })
  }

编辑:这是上面代码显示所需的模板。

<form [formGroup]="feedbackForm" novalidate (ngSubmit)="send()">
    <div formArrayName="questions">
        <div *ngFor="let question of feedbackForm.get('questions').controls; let i=index;">
            <p>{{feedbackForm.get(['questions',i,'description']).value}}</p>
            <div [formGroupName]="i">
        <div formArrayName="answers">
          <div *ngFor="let ans of feedbackForm.get(['questions',i,'answers']).controls; let j = index">
              <div [formArrayName]="j">
                <input formControlName="description" />
              </div>
          </div>
        </div>
            </div>
        </div>
    </div>

    <input type="submit" value="Send">
</form>

<pre> {{feedbackForm.value | json}} </pre>

推荐阅读