html - 如何让多个单选按钮在 Angular2 中工作?

标签 html angular typescript

我有一个 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 中我需要两个问题,每个问题有两个按钮,对于每个问题我应该能够选择一个单选按钮。 但就我而言,我只能选择一个单选按钮,当我转到第二个问题时,所选的第一个问题将变为未选中状态。 让我知道如何从每个问题中选择一个单选答案。

最佳答案

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

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

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

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

关于html - 如何让多个单选按钮在 Angular2 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542591/

相关文章:

css - 解决 div 定位问题

html - 表格单元格内部时的 CSS z-index 问题

javascript - 我应该学习 Flash/Flex/ActionScript 还是 HTML/CSS/JS ("HTML5")?

Angular2 表行作为组件

angular - angular-cli 中 .DS_Store 文件的 Broccoli MergeError

javascript - 为什么 "reject"在此代码中实际上并未拒绝?

javascript - 是否可以在没有服务器的情况下从客户端应用程序中的 API GITHUB 获取 token 和 client_id ?

带有模板字符串的 Javascript URL

html - 我的链接不起作用(应该很简单)

Angular 树抖动不剥离开发代码,我应该寻找什么?