Handling multiple radio buttons in a Quiz Angular 5

自作多情 提交于 2020-03-24 00:34:25

问题


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

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.


回答1:


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 = [];


来源:https://stackoverflow.com/questions/50772057/handling-multiple-radio-buttons-in-a-quiz-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!