3

I'm new to Angular and Implementing a Quiz containing multiple MCQs. But I am having trouble in radio button selection.

My Questions are coming from the database and Options too.

mcq.component.html

<form (ngSubmit)="ff.form.valid && answer(ff)" #ff="ngForm">
  <div *ngFor="let question of questions">
    <p style="font-size: 25px;">{{question.title}}</p>
    <div *ngFor="let option of question.options">
        <input [(ngModel)]="option_model.selected_option_id" #selected_option_id="ngModel" type="radio" value="{{option.id}}" name="{{question.id}}">
        <!-- <input type="radio" value="{{option.id}}" name="{{question.id}}" ngModel > --> //This way it works fine but I need to use [(ngModel)] to submit the form
      {{option.title}}
    </div>
  </div>
  <input style="float: right" type="submit" value="Submit"/>
</form>

Note: The {{question.id}} is unique for each question. Also, this works well if I remove the [(ngModel)] attribute.

And here is what I'm trying to accomplish And here is what I'm trying to accomplish

The Problem: When I select an option from the second question it deselects the selected option from the First Question. Means I am only able to select one option from both questions.

Please Help me, what I am doing wrong. I've been stuck here for two days.

Adnan Sheikh
  • 760
  • 3
  • 13
  • 27
  • Possible duplicate of [Multiple radio button groups in one form](https://stackoverflow.com/questions/28543752/multiple-radio-button-groups-in-one-form) – Tewdyn Jun 09 '18 at 08:13
  • Check if this {{question.id}} is diffrent for all ques? Cause this can only happen if you have radio buttons with same name attribute for different questions. – Nandita Sharma Jun 09 '18 at 08:14
  • Yes the {{question.id}} is different for both questions. This works when I remove [(ngModel)] attribute, But then I can't get the value when submitting form. – Adnan Sheikh Jun 09 '18 at 08:16
  • Seems some issue with the way you are using ngModel with radio buttons ! Share some fiddle where I can check whats the issue – Nandita Sharma Jun 09 '18 at 08:37
  • I don't know how to do that :( – Adnan Sheikh Jun 09 '18 at 08:59

1 Answers1

0

Okay, Git it Sorted. The issue was with the ngModel and name attribute

It works fine like this

<input [(ngModel)]="options[question.id]" [checked]="options[question.id]" value="{{question.id}}-{{option.id}}" type="radio"
      name="option{{question.id}}">

And in typescript

options: any = [];
option: any = [];
Adnan Sheikh
  • 760
  • 3
  • 13
  • 27