如何使用嵌套表单数组将服务器响应映射到有角反应式表单

时间:2019-03-07 10:46:05

标签: angular nested angular-reactive-forms formarray

我正在使用反应形式方法在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">

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

2 个答案:

答案 0 :(得分:1)

您在做些“倒置”。 正确的方法是遍历数组的每个成员并为其创建控件,转到嵌套数组,为其创建控件,然后将其推送到问题数组。

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>

答案 1 :(得分:1)

阿卜杜勒(Abdul)有两个不同之处

  1. “提出问题的结构”
  2. 表格

,但您尚未定义表单。为此,您需要知道如何将数据发送到服务器。我一定要向您发送类似的邮件给服务器

[1,3,1]
//or
[{question:1,answer:1},{question:2,answer:3},{question:3,answer:1}]
//or
[
   {question:'why didn't you turn up',answer:'Unexpected Official Work'},
   {question:'why didn't you do down',answer:'I don't know'}
]

如您所见,无论如何,您只需要一个唯一的formArray,就可以使用服务器的响应来创建表单的视图,而无需创建formArray

您要发送到服务器什么?

好吧,如果我们选择第三个选项,则是FormArray,而不是formGroup。不要管它FormArray可以像FormGroup一样管理。首先,我们将了解如何创建表格Array

 ngOnInit() {
    this.feedbackForm = new FormArray(this.data.map(x=>new FormGroup({
      'question':new FormControl(x.description),
      'answer':new FormControl('')
    })))
  }

请参阅feedbackform是一个表单数组。如何创建呢?对于每个问题,创建一个带有两个Form控件的formGroup,分别是问题和答案

.html变得像

<form *ngIf="feedbackForm" [formGroup]="feedbackForm" (submit)="send()">
      <div *ngFor="let control of feedbackForm.controls;let i=index"   >
        <div [formGroup]="control">
          <input formControlName="question">
          <div *ngFor="let a of data[i].answers">
            <label>
              <input type="radio" [value]="a.description" formControlName="answer">
              <span>{{a.description}}</span>
            </label>
          </div>
        </div>

        </div>
      <button type="submit">submit</button>
    </form>

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

看到,我们使用“数据”显示收音机的标签并为收音机赋予价值,但是Form只是一个表单数组。如果我们的“数据”具有问题和答案的“ id”,我们可以使用它

请参见stackblitz

注意:我只是在stackblitz中添加一个带有FormArray的典型FormGroup,因为它与.html不同。