简体   繁体   English

角度ng对于单选按钮

[英]Angular ngFor radio buttons

I've got a few questions like 'what is something' and 4 radio buttons as answers. 我有一些问题,例如“什么是东西”和4个单选按钮作为答案。 So it`s like 3 generated <ul> s in DOM. 因此,就像DOM中3个生成的<ul>一样。 But the problem is, when I click some radio button, it selects the radio button in another question. 但是问题是,当我单击某个单选按钮时,它在另一个问题中选择了单选按钮。 How to fix this problem? 如何解决这个问题? Is it something with the value? 有价值吗? Or it needs to have some unique index? 还是需要一些独特的索引?

Code: 码:

<ul *ngFor="let test of tests"> {{test.question.title}}
    <li *ngFor="let answer of test.question.answers"> <input type="radio" [value]="answer" [(ngModel)]="radioSelected"> <label for="">{{answer}}</label> </li>
</ul>

<button (click)="check(radioSelected)">Send</button>

add name attribute base of index and create an answer object in the component 添加索引的名称属性库,并在组件中创建答案对象

component 零件

answers = {}; // 👈

template (view) 模板(视图)

<ul *ngFor="let test of tests;let index = index"> {{test.question.title}}
    <li *ngFor="let answer of test.question.answers"> 
       <label >
         <input [name]="index" type="radio" [value]="answer" [(ngModel)]="answers[index]"> 
         {{answer}}</label> 
    </li>
</ul>

<button (click)="check(answers)">Send</button>

stackblitz demo 🚀🚀 stackblitz演示🚀🚀

您应该为ngFor中的每个测试使用不同的ngModel,将ngModel更改为

<input type="radio" [value]="answer" [(ngModel)]="test.question.radioSelected">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM