如何使用角反应形式的嵌套数组字段构建字段数组?

时间:2018-07-11 15:29:00

标签: javascript angular typescript angular-reactive-forms

我有一个负责创建调查的表格。 每个调查都有问题,每个问题都有选项。

调查可能有很多问题。

问题可以有很多选择。

因此,我需要类似下面的屏幕快照。

enter image description here

1 个答案:

答案 0 :(得分:1)

检查一下。我正在使用FormGroupArray创建动态的问题/选项列表。

// Component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  public view: any;
  surveyForm: FormGroup;
  surveyQuestions: FormArray;
  surveyOptions: any[] = [];
  formData: string;
  constructor(private formbuilder: FormBuilder)  {
  }
  ngOnInit() {
    this.surveyForm = this.formbuilder.group({
      survey: this.formbuilder.array([this.createSurveyQuestion()])
    });
  }

  createSurveyQuestion(): FormGroup {
    return this.formbuilder.group({
      question: [''],
      options: this.formbuilder.array([this.createOption()])
    });
  }
  createOption(): FormGroup {
    return this.formbuilder.group({
      option: ['']
    });
  }

  addQuestion(): void {
    this.surveyQuestions = this.surveyForm.get('survey') as FormArray;
    this.surveyQuestions.push(this.createSurveyQuestion());
  }
  addOption(indx: number): void {
    let questCtrl =  <FormArray>this.surveyForm.get('survey');
    let m = questCtrl.controls[indx];
    let opts = m.get('options') as FormArray;
    opts.push(this.createOption());
  }
  get getSurveyControls() {
    return <FormArray>this.surveyForm.get('survey');
  }
  getQuestionOptionControls(questIndex: number){
    let questCtrl =  <FormArray>this.surveyForm.get('survey');
    let m = questCtrl.controls[questIndex];
    let opts = <FormArray>m.get('options');
    return opts;
  }
  convertFormData() {
    this.formData = JSON.stringify(this.surveyForm.value);
  }
}

模板-

// Template 
<form [formGroup]="surveyForm">
    <button (click)="addQuestion()">Add Question</button>
  <div formArrayName="survey" *ngFor="let quest of getSurveyControls.controls; index as i;" [attr.data-index]="i">
    <div [formGroupName]="i">
      <input formControlName="question" placeholder="Question"/>
      <button (click)="addOption(i)">Add Option</button>
      <div formArrayName="options" *ngFor="let opt of getQuestionOptionControls(i).controls; index as oidx;"[attr.data-index]="oidx">
        <div [formGroupName]="oidx">
          <input formControlName="option" placeholder="option"/>
        </div>
      </div>
    </div>
  </div>
</form>

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