您好,谢谢您的宝贵时间。感谢@Steve:
如何在嵌套循环中从表单中检索FormArray? 第一个循环在哪里: 常量问题= this.form.controls.questions作为FormArray; 和 我如何提出答案 常量答案= this.form.controls.questins.answers是因为FormArray无法正常工作?
HTML:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngFor="let data of (form.controls.questions as FormArray); let iindex = index">
<div> {{ iindex + 1 }}. {{ question.questTxt }}</div>
<div *ngFor="let answer of questions; let iindex=index;"
formArrayName="questions">
<radio-button
[radioId]="answer.answerId"
[radioName]="question.id"
[radioOptionTxt]="answer.answer"
></radio-button>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
myData() {
return [
{ id: 100, name: 'It is Name 1', questTxt: 'I like animals and I have',
'answers': [{answerId: 10, answer: 'Dog'},
{answerId: 11, answer: 'Cat'},
{answerId: 12, answer: 'Rabbit'}]},
{ id: 200, name: 'It is Name 2', questTxt: 'I like drawing by',
'answers': [{answerId: 20, answer: 'Pencil'},
{answerId: 21, answer: 'Ink'},
{answerId: 22, answer: 'Oil'},
{answerId: 23, answer: 'Sangina'}]},
{ id: 300, name: 'It is Name 3', questTxt: 'The color of my dog is',
'answers': [{answerId: 30, answer: 'white'},
{answerId: 31, answer: 'black'},
{answerId: 32, answer: 'white and black'},
{answerId: 33, answer: 'orange'}]},
{ id: 400, name: 'It is Name 4', questTxt: 'This year I visited',
'answers': [{answerId: 40, answer: 'England'},
{answerId: 41, answer: 'Germany'},
{answerId: 42, answer: 'Canada'},
{answerId: 43, answer: 'Israel'}]},
];
}
}
答案 0 :(得分:1)
您需要的是Reactive Forms的FormArray选项。
如果您的JSON回传了定义问题和答案的对象列表,则可以将其插入到FormGroup控件内不断增长的FormArray中。
this.formGroup = new FormBuilder.group({
...
questions: this.formBuilder.array([])
})
然后,当您拥有数据并准备填写表格时:
var questions = this.formGroup.controls.questions as FormArray;
现在循环遍历返回为JSON的对象,并将每个项目添加到问题数组。
在HTML方面,您可以遍历问题控件:
*ngFor="let question of formGroup.controls.questions?.value"
这是一个(非常)简短的例子。我建议在线查看更多材料,因为FormArrays学习起来很棘手,错误也很难定位。
编辑:遍历数据 好的,假设您有一个带有问题的JSON数组,则可以将它们添加到FormArray中:
var questions = this.formGroup.controls.questions as FormArray;
this.questionsJSON.forEach(question => {
questions.push(question);
})
console.log(this.formGroup.controls.questions); // should see the question as values of the FormArray