I currently faced the issue of building the form on multiple choice questions. At this moment, the form for single choice works well, only left multiple choice questions. The goal I want to have is something like this:
{
"questions": [
// if multiple choices question
{
"question_id": 17,
"answer_ids": [81,82,83]
},
{
"question_id": 20,
"answer_ids": [101,102,104]
}
]
}
survey.ts
this.surveyForm = this.formBuilder.group({
questions: formBuilder.array([])
})
for (var i = 0; i < this.questions.length; i++) {
if(this.questions[i].question_type == '2') {
// get multiple
let question = formBuilder.group({
question_id: [this.questions[i].id, Validators.required],
answer_ids: formBuilder.array([])
});
this.surveyForm.controls['questions'].push(question);
// for (var j = 0; j < this.questions[i].answers.length; j++) {
// console.log(j);
// let answer = formBuilder.array(this.questions[i].answers)
// console.log(answer)
// this.questions[i].answers[j].push(new FormControl());
// this.surveyForm.controls['questions'].controls['answer_ids'].push(new FormControl('', [Validators.required]))
// };
console.log('m')
}
}
survey.html
<div *ngIf="surveyForm">
<form [formGroup]="surveyForm">
<div formArrayName="questions">
<div *ngFor="let question of questions; let i = index" [formGroupName]="i" padding-bottom>
<ion-row>
<ion-col col-2>
<h5>{{ i + 1 }}.</h5>
</ion-col>
<ion-col col-10>
<h5>{{ question.text }}</h5>
<p>{{ question.instruction }}</p>
<div *ngIf="question.question_type == 1; else multiple_choice">
<ng-template #multiple_choice>
<ion-list formArrayName="answer_ids">
<div *ngFor="let choice of question.answers; let i = index">
<ion-item>
<ion-label style="white-space: normal;">{{ choice.id }}</ion-label>
<ion-checkbox (ionChange)="onChange(choice.id, $event._checked)" value="choice.id"></ion-checkbox>
</ion-item>
</div>
</ion-list>
</ng-template>
</ion-col>
</ion-row>
</div>
</div>
</form>
</div>
What could be the best way that I can get the value id from each multiple choice checkbox to push into the array of specific question?