3

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>
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • Please refer this: https://stackoverflow.com/questions/44158712/angular-2-reactive-form-for-each-table-row This will help you to solve your problem. – Gourav Pokharkar Dec 03 '17 at 13:42

2 Answers2

3

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

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

You should have different ngModel for every test in ngFor, change your ngModel to

<input type="radio" [value]="answer" [(ngModel)]="test.question.radioSelected">
NTP
  • 4,338
  • 3
  • 16
  • 24