Selem Selem - 4 months ago 64x
AngularJS Question

Wrong behavior while checking radio buttons in a Loop (using Angular2)

I'm working on an

project & currently i'm stuck with a Quizz module, so illustrating the problem ; when a candidate wants to pass a test he will get that test with some questions ; every question has 4 propositions with radio buttons and he should answer merely by checking one of them for every question. here is the HTML snippet of what i'm talking about :

<div *ngFor="#qt of listQuestion">

<h3 class="uk-accordion-title" >{{qt.wordingQ}}</h3>

<div class="uk-accordion-content">

<input type="radio" id="radio_demo_1" />

<label for="radio_demo_1"> <b>{{qt.lpo[0]}}</b></label> <br><br>

<input type="radio" id="radio_demo_2" />

<label for="radio_demo_2"><b>{{qt.lpo[1]}}</b></label><br><br>

<input type="radio" id="radio_demo_3" />

<label for="radio_demo_3"> <b>{{qt.lpo[2]}}</b></label> <br><br>

<input type="radio" id="radio_demo_4" />

<label for="radio_demo_4"><b>{{qt.lpo[3]}}</b></label>

</div> </div>

Where the
is a list of Question entities which each one of them has a
and a list of propositions (
), in that way i cannot check only one radio button for every question as it is shown below : enter image description here
I tried to remove the
in the
<input> tags
and it still the same problem , I've changed the
and give the same name for all tags thus, I could check only one proposition but when moving to another question and checking a new proposition , the first one will be cleared.
Any help Please ?


Your problem is that the way you currently do it, you have a single radio group for all questions. You can solve it by creating radio element name attributes dynamically. Something like this:

<h3 class="uk-accordion-title" >{{}}</h3>

      <input type="radio" id="radio_demo_{{}}_{{index$}}" name="radio_demo_{{}}_{{index$}}" />

      <label for="radio_demo_{{}}_{{index$}}"> <b>{{qt.lpo[0]}}</b></label> <br><br>

{{}} (or any other qt property that uniquely identifies the question) is the key here.

This way, you'll have a separate radio group for each question, because group names won't intersect.