0
votes

In my code I have data for questions which construct a nested form dynamically. there are two types of questions 'Multiple' and 'Single'

I have some code in the link given below for a form in my page. Based on the question type in each questions I might want to show the options if its mat-checkbox or mat-radio button.

https://stackblitz.com/edit/angular-uezhjg

While accessing the FormControlName response_options for question type Multiple I am able to use Mat Check box properly but when I try the same for radio I have a problem this isn't working fine. I have commented the code which does that part. How do I achive this ?

2
I do not see radio in your code snippet and what does it mean that isn't working fine? Could you also organize your code int snippet HTML because it is hard to read?Stefan
I have formatted the HTML, and added the snippet where I have tried to implement mat-radio from the options of each question. It has been commented though.Shahabaz

2 Answers

0
votes

You have to update your html because in your case {{j}} is not known in div for a single question.

<div *ngIf="take_exam_form">
<form [formGroup]="take_exam_form" (submit)="submitAnswers()">
    <div class="question" formArrayName="questions" *ngFor="let question of take_exam_form.controls.questions.controls;let i = index">
        <hr>
        <div formGroupName="{{i}}">
            <div class="question"> {{i+1}}.) {{question.value.question}} </div>
            <ng-container formArrayName="response_option" *ngFor="let response_option of question.controls.response_option.controls;let j = index">
            <div *ngIf="question.value.question_type == 'multiple'">

                    <div formGroupName={{j}}>
                        <mat-checkbox formControlName="answered"> {{response_option.value.option_value}} </mat-checkbox>
                    </div>

            </div>
            <div *ngIf="question.value.question_type == 'single'">
                  <div formGroupName={{j}}>
                      <mat-radio-group
                      aria-labelledby="example-radio-group-label"
                      formControlName="answered"
                      class="example-radio-group">
                      <mat-radio-button class="example-radio-button">
                          {{response_option.value.option_value}} 
                      </mat-radio-button>
                    </mat-radio-group>
                   </div>
              </div>
              </ng-container>
        </div>
    </div>
    <hr>
    <button mat-raised-button color="primary" type="submit">Submit Answers</button>
</form>

0
votes

I think its a basic idea while using Radio Buttons that it will have only one value as a result whereas checkboxes will have values as many checkboxes it can have. I altered the code to fetch answered attribute at questions level for a "single" type of questions and answered at options level for "multiple" type of questions.