I'm developing a feedback form in Angular using reactive forms approach. The response from the server has questions array which in turn has answers array.
Here is the response.
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"
}
]
}
]
I'm trying to build reactive form as follows.
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([])
})
}
How to map the question and response to my reactive form.
I tried as follows, but never works,
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 || []));
}
}
Here is my template
<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">
I'm trying to display question with answers and I need user to select answer for the question and on submit I need the selected answer values.