Angular 6 - 从响应式表单访问数组中的数组

Angular 6 - access array in array from a ReactiveForm

我有以下表格

    this.questionForm = this.fb.group({
      title: [],
      questions: this.fb.array(
        [
          this.fb.group({
            question: [],
            answers: this.fb.array([this.fb.group({answer: ''})])
          })
        ]
      )
    });
  }

我对循环问题没有任何问题。但是我不完全确定如何从我的模板访问答案数组。

这是我目前在模板中的内容

<div formArrayName="questions">
  <div class="form-row" *ngFor="let question of questions.controls; let questionIndex=index" [formGroupName]="questionIndex">
    <button (click)="test(1)"></button>
    <div class="col">
      <textarea formControlName="question" class="form-control" placeholder="Enter your question here" rows="6"></textarea>
    </div>
    <div class="col">
      <!-- Here I want to loop trough the questions but i am not sure how-->
    </div>
  </div>
</div>

那么我应该怎么做才能遍历答案?

您需要在屏幕上的 FormArray 中有一个 FormArray。它应该是这样的:

<div formArrayName="questions">
    <div class="form-row" *ngFor="let question of questions.controls; let questionIndex=index" [formGroupName]="questionIndex">
        <button (click)="test(1)"></button>
        <div class="col">
            <textarea formControlName="question" class="form-control" placeholder="Enter your question here" rows="6"></textarea>
        </div>
        <div class="col" formArrayName="answers">
            <div class="form-row" *ngFor="let answer of getAnswers(question).controls; let j=index" [formGroupName]="j">
                <input type="text" formControlName="answer" />
            </div>
        </div>
    </div>
</div>

getAnswers 方法可能类似于:

getAnswers(question): FormArray {
    const answers = question.get('answers') as FormArray;

    return answers;
}

我没有测试过这段代码,但你通常会这样做。

它只是以与迭代问题相同的方式为每个问题循环 answers 数组。与 Husein 提供的答案相反,我不会在迭代中调用函数,因为它会在每次变化检测时被调用,这是 经常 尤其是当你可以有很多绑定。所以我在模板中要做的是(缩短代码)...

<form [formGroup]="questionForm">
  <div formArrayName="questions">
    <div *ngFor="let quest of questionForm.get('questions').controls; let questionIndex=index" [formGroupName]="questionIndex">
      <textarea formControlName="question"></textarea>
      <div formArrayName="answers">
        <div *ngFor="let answ of quest.get('answers').controls; let i = index" [formGroupName]="i">
          <input formControlName="answer">
        </div>
      </div>
    </div>
  </div>
</form>

演示:StackBlitz