使用Angular 6处理单选按钮 [英] Handling radio buttons with Angular 6

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

问题描述

我有一个问题列表,如下所示.

I have a list of questions as given below.

  public questionList = [
    {
      question:{
        id: "Q1",
        query:"query 1"
      },
      options:[
        {
          id: "opt1",
          text: "Q1_opt1"
        },
        {
          id: "opt2",
          text: "Q1_opt2"
        }
      ],
      selected:{
        id:"",
        text:""
      }
    },

    {
      question:{
        id: "Q2",
        query:"query 2"
      },
      options:[
        {
          id: "opt1",
          text: "Q2_opt1"
        },
        {
          id: "opt2",
          text: "Q2_opt2"
        }
      ],
      selected:{
        id:"",
        text:""
      }
    }
  ];

我的目的是列出问题以及选项作为单选按钮.每当有人选择一个选项时,应将所选选项的ID分配给与该问题相关联的"selected.id".

My intention is to list the questions along with options as radio buttons. Whenever somebody selects an option, the id of the selected option should be assigned to "selected.id" which is associated with that question.

以下是HTML部分.

<div *ngFor="let question of questionList">
    {{question.question.query}}

    <br>
    <div *ngFor="let option of question.options">
      <input type="radio" value="{{option.id}}" [(ngModel)]="question.selected.id">{{option.text}}
      <br>
    </div>
    {{question.selected | json}}

    <br>
    <br>


</div>

但是当我为第一个问题选择任何选项时,第二个问题的选项也会被选中,反之亦然.

But when i select the any option for the first question, option for the second question is also getting selected and vise versa.

这里出什么问题了?

推荐答案

您在广播中缺少 name 属性.名称对于一组选项应该是唯一的.

You are missing name attribute on radio. The Name should be unique for one set of Options.

在动态生成单选按钮的用例中,您可以使用循环索引来设置名称,如下所示-

In your use case where radio buttons are genrated dynamically you can use index of loop to set name like this -

<div *ngFor="let question of questionList; let i = index">
    {{question.question.query}}

    <br>
    <div *ngFor="let option of question.options; let j = index">
      <input type="radio" [value]="option?.id" [(ngModel)]="question.selected.id" [name]='"abc"+i+j'>{{option.text}}
      <br>
    </div>
    {{question.selected | json}}
</div>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆