【发布时间】:2019-07-29 05:29:39
【问题描述】:
我正在使用响应式表单方法在 Angular 中开发反馈表单。 来自服务器的响应包含 questions 数组,而 questions 数组又包含 answers 数组。
这是回复。
value": [
{
"description": "why didn't you turn up"
"answers": [
{
"description": "Unexpected Personal Committment"
},
{
"description": "Unexpected Official Work"
},
{
"description": "Even Not What I Expected"
},
{
"description": "Did Not Receive Further Information About The Event"
},
{
"description": "Incorrectly Registered"
},
{
"description": "Do Not Wish to Disclose"
}
]
}
]
我正在尝试如下构建反应式表单。
ngOnInit() {
this.feedbackForm = this.fb.group({
questions: this.initQuestion()
})
}
initQuestion() {
return this.fb.group({
description: [],
answers: this.initAnswer()
})
}
initAnswer() {
return this.fb.group({
description: this.fb.array([])
})
}
如何将问题和响应映射到我的反应形式。
我尝试如下,但始终没有成功,
get questions(): FormArray {
return <FormArray>this.feedbackForm.get('questions');
}
get answers(): FormArray {
return <FormArray>this.feedbackForm.get('questions').get('answers');
}
displayQuestions(questions: Response<Question[]>): void {
if (this.feedbackForm) {
this.feedbackForm.reset();
}
this.questionsResponse = questions;
if (this.questionsResponse.value.length > 0) {
this.feedbackForm.setControl('questions', this.fb.array(this.questionsResponse.value || []));
this.feedbackForm.setControl('answers', this.fb.array(this.questionsResponse.value.answers || []));
}
}
这是我的模板
<form [formGroup]="feedbackForm" novalidate (ngSubmit)="send()">
<div formArray="questions">
<div [formGroup]="i" *ngFor="let question of feedbackForm.controls.questions.controls; let i=index;">
<p>{{question.description}}</p>
<div formArray="answers">
<div [formGroup]="j" *ngFor="let answer of question.controls.answers.controls; let j=index">
<label [attr.for]="j">{{answer.description}}</label>
<input type="radio" [id]="j" [formControlName]="j" value="{{answer.descripiton}}" />
</div>
</div>
</div>
</div>
<input type="submit" value="Send">
我正在尝试显示带有答案的问题,我需要用户为问题选择答案,并且在提交时我需要选择的答案值。
【问题讨论】:
-
发布您的模板。你也可以做一个 StackBlitz 例子
-
@ritaj : 这是我的场景的StackBlitz
标签: angular nested angular-reactive-forms formarray