【问题标题】:How to get multiple radio buttons to work in angular2?如何让多个单选按钮在 angular2 中工作?
【发布时间】:2017-11-16 11:27:02
【问题描述】:

我有一个 json 数组,类似这样:

questions = 
 [
    {
       title: Your section is?
       choices: [
                   {
                      id: 1,
                      label: "TestA"
                   },
                   {
                      id=2,
                      label: "TestB"
                   }
                ]
    },
    {
       title: Your major is?
       choices: [
                   {
                      id=3,
                      label: "Medicine"
                   },
                   {
                      id=4,
                      label: "Engineering"
                   }
                ]
    }
 ]

我的html:

<div *ngFor="let choice of questions">
   <div *ngFor="let choice of questions.choices;let i=index">
    <div class="radio-group" (click)="onSelectChoice(choice.id)">
      <input type="radio" class="hide" name="choiceElements" [value]="choice.id" id="choice.label" formControlName="choiceElements">
      <label [class.selected]="choice.id === selctedRadio" for="{{choice.label}}" class="" >{{choice.label}}</label>
    </div>
  </div>
</div>

我的 TS:

selctedRadio: '';
onSelectChoice(selctedChoice: any){
  this.selctedRadio = selctedChoice;
}

因此,在 html 中我需要两个问题,每个问题有两个按钮,对于每个问题,我应该能够选择一个单选按钮。 但在我的情况下,我只能选择一个单选按钮,当我转到第二个问题时,选定的第一个问题将变为未选中状态。 告诉我如何从每个问题中选择一个单选答案。

【问题讨论】:

  • 你在使用响应式表单吗?似乎您使用的是formControlName,但其余的看起来不像是反应形式?

标签: html angular typescript


【解决方案1】:

您的单选按钮必须具有相同的名称当且仅当它们属于同一组。

您必须找到一种方法来为每个组创建一个唯一的名称。

顺便说一句,这不是特定于角度的,它只是单选按钮在纯 HTML 中的工作方式。

但是,有关如何以角度处理单选按钮的更多信息,您可以查看以下内容: Angular2 ReactiveFormsControl: how to bind radio buttons? Angular2 - Radio Button Binding

【讨论】:

  • 我通过给每个单选按钮组一个唯一的名称解决了这个问题
猜你喜欢
  • 1970-01-01
  • 2016-07-18
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多