遍历 Angular 中的嵌套 FormArray 2

Traversing a nested FormArray in Angular 2

我正在尝试遍历嵌套的 FormArray 以跟踪一组问题,每个问题都有自己的 'FormControl'。我创建了一个名为 'groups' 的 FormArray。层次结构为 Groups[Questions[Answers]]

constructor(private surveyService: SurveyService, @Inject(FormBuilder) private fb: FormBuilder) {
    this.survey = <Survey>SURVEYS[0];

    this.reactiveForm = fb.group({
      name: ['', Validators.required],
      groups: fb.array(this.getGroups())
    });

}

getGroups() : AbstractControl[] {
    return Array.apply(null,
      Array(this.survey.groups.length)).map((x, index) => new FormArray(this.getQuestions(index)))
  }

getQuestions(index) : AbstractControl[] {
    return Array.apply(null,
      Array(this.survey.groups[index].questions.length)).map(x => new FormControl(x, Validators.required));
  }

这是我的 HTML 代码:

<form [formGroup]="reactiveForm">
  <div formArrayName="groups">
    <div *ngFor="let group of survey.groups; index as groupIndex" [formArrayName]=groupIndex>
      <h1>{{group.groupName}}</h1>
      <div *ngFor="let question of group.questions; index as questionIndex" [formArrayName]=questionIndex>
        <h2>{{question.question}}</h2>
        <label *ngFor="let answer of question.responses ; index as answerIndex">
          <input type="radio" [value]=answerIndex [formControlName]=questionIndex>{{answer}}
        </label>
      </div>
    </div>
  </div>
</form>

我认为它是这样工作的:第一个 ngFor 提取问题数组,第二个 ngFor 提取答案数组,然后最后一个 ngFor 使用 [formControlName] 将每个问题绑定到同一个控件,给它一个唯一的答案。但是,我得到的错误是:

Error: Cannot find control with path: 'groups -> 0 -> 0 -> 0'

如果Groups[0]是一个数组,Groups[0][0]也是一个数组,为什么那个[0]突然不存在了?应该如何遍历这样的 FormArray?

对于演示,我使用了简单的结构:

export class Group {
  title: string;
  questions: Question[] = [];

}

export class Question {
  title: string;
  answers: Answer[] = [];    
}

export class Answer {
  id: number;
  title: string;
}

StackBlitz Demo

这是您创建的内容:

现在看看你的模板:

<form [formGroup]="reactiveForm">
  <div formArrayName="groups">
    <div ... [formArrayName]=groupIndex>
      ...
      <div ... [formArrayName]=questionIndex>
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             Do you see such FormArray in your FormGroup? I don't
        <...
        <label *ngFor="let answer of question.responses ; index as answerIndex">
          <input ...[formControlName]=questionIndex>...
        </label>
      </div>
    </div>
  </div>
</form>

如您所见,Angular 无法通过路径 groups -> 0 -> 0 -> 0 找到 FormControl,因为它应该是 groups -> 0 -> 0

因此,如果您删除多余的 [formArrayName]=questionIndex 指令,那么它应该可以工作。

Ng-run Example

提示:使用<pre>{{reactiveForm.value | json}}</pre>测试FormGroup结构