在 Quiz Angular 5 中处理多个单选按钮 [英] Handling multiple radio buttons in a Quiz Angular 5

查看:18
本文介绍了在 Quiz Angular 5 中处理多个单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 的新手,正在实施包含多个 MCQ 的测验.但是我在选择单选按钮时遇到了问题.

我的问题也来自数据库和选项.

mcq.component.html

<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 >-->//这种方式工作正常,但我需要使用 [(ngModel)] 来提交表单{{option.title}}

<input style="float: right" type="submit" value="Submit"/></表单>

注意:每个问题的 {{question.id}} 都是唯一的.此外,如果我删除 [(ngModel)] 属性,这会很有效.

这就是我想要完成的

问题:当我从第二个问题中选择一个选项时,它会从第一个问题中取消选择所选的选项.意味着我只能从两个问题中选择一个选项.

请帮帮我,我做错了什么.我被困在这里两天了.

解决方案

好的,Git it Sorted.问题在于 ngModel 和 name 属性

它像这样工作得很好

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

在打字稿中

options: any = [];选项:任何= [];

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.

解决方案

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

这篇关于在 Quiz Angular 5 中处理多个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆