我有以下表格
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>
那我该怎么做才能遍历答案?
答案 0 :(得分:0)
您将需要在屏幕上的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;
}
我尚未测试此代码,但这是您通常会执行的方式。
答案 1 :(得分:0)
它只是以迭代您的问题的相同方式,为每个问题循环array (size=9)
'id' => int 1
'question_id' => int 55
'step_1' => string '[["$50,000-$100,000","More than $100,000"]]' (length=43)
'step_2' => string '[["Step2-option1","Step2-option2","Step2-option3"]]' (length=51)
'step_3' => string '[["Step3-option2"]]' (length=19)
'step_4' => null
'step_5' => null
'created_at' => string '2018-10-03 12:29:05' (length=19)
'updated_at' => string '2018-10-03 12:29:05' (length=19)
数组。与Husein提供的答案相反,我不会在迭代中调用函数,因为它将在每次更改检测时被调用,这通常经常,特别是当您有很多绑定时。所以我要在模板中做的是(缩短代码)...
answers
演示: StackBlitz