簡體   English   中英

在Angular 2中遍歷嵌套的FormArray

[英]Traversing a nested FormArray in Angular 2

我試圖遍歷嵌套的FormArray來跟蹤一組問題,每個問題都有自己的“ FormControl”。 我已經創建了一個名為“ groups”的FormArray。 層次結構進入小組[問題[答案]]

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?

這是您創建的:

在此處輸入圖片說明

現在看一下您的模板:

<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運行示例

提示:使用<pre>{{reactiveForm.value | json}}</pre> <pre>{{reactiveForm.value | json}}</pre>測試FormGroup結構

對於演示,我使用了簡單的結構:

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

}

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

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

StackBlitz演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM