Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 379
Jack Rassel Avatar asked Jul 13 '26 04:07

Jack Rassel


1 Answers

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 🚀🚀

like image 78
Muhammed Albarmavi Avatar answered Jul 15 '26 20:07

Muhammed Albarmavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!