简体   繁体   中英

Angular ngFor radio buttons

I've got a few questions like 'what is something' and 4 radio buttons as answers. So it`s like 3 generated <ul> s in DOM. 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 🚀🚀

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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