2

I have a array of json, something similar to this:

questions = 
 [
    {
       title: Your section is?
       choices: [
                   {
                      id: 1,
                      label: "TestA"
                   },
                   {
                      id=2,
                      label: "TestB"
                   }
                ]
    },
    {
       title: Your major is?
       choices: [
                   {
                      id=3,
                      label: "Medicine"
                   },
                   {
                      id=4,
                      label: "Engineering"
                   }
                ]
    }
 ]

My html:

<div *ngFor="let choice of questions">
   <div *ngFor="let choice of questions.choices;let i=index">
    <div class="radio-group" (click)="onSelectChoice(choice.id)">
      <input type="radio" class="hide" name="choiceElements" [value]="choice.id" id="choice.label" formControlName="choiceElements">
      <label [class.selected]="choice.id === selctedRadio" for="{{choice.label}}" class="" >{{choice.label}}</label>
    </div>
  </div>
</div>

My TS:

selctedRadio: '';
onSelectChoice(selctedChoice: any){
  this.selctedRadio = selctedChoice;
}

So, in html I need two questions, each question having two buttons, for each question I should be able to select one radio button. But in my case, I am able to select only one radio button and when I go to second question the selected first question becomes unselected. Let me know how I can be able to select one radio answer from each question.

Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • are you using reactive form? Seems you are using `formControlName`, but the rest doesn't look like a reactive form? – AT82 Jun 14 '17 at 14:41

1 Answers1

2

Your radio buttons must have the same name if and only if they belong to the same group.

You will have to find a way to create a unique-per-group name.

By the way, this is not angular specific, it's just how radio buttons work in plain HTML.

however, for more info about how to handle radio buttons in angular, you can check this : Angular2 ReactiveFormsControl: how to bind radio buttons? Angular2 - Radio Button Binding

Pac0
  • 21,465
  • 8
  • 65
  • 74