gpt4 book ai didi

javascript - 遍历 Angular 2 中的嵌套 FormArray

转载 作者:行者123 更新时间:2023-12-01 02:10:15 25 4
gpt4 key购买 nike

我试图遍历嵌套的 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] 将每个问题绑定(bind)到同一个控件,给出这是一个独特的答案。但是,我得到的错误是这样的:

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

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

最佳答案

这是您创建的内容:

enter image description here

现在看看你的模板:

<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结构

关于javascript - 遍历 Angular 2 中的嵌套 FormArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com