Wira Xie
Wira Xie

Reputation: 839

Radio buttons only one can be chosen because *ngFor

I'm trying to make something like questionnaire form with some questions in it and multiple choice options using radio button.

The questions and options are from a json file.

Then i use nested ngFor to separate the parent and the child for each questions and options.

But looks like i'm doing it wrong.

The radio buttons that resulted from ngFor make only one that can be chosen among all.

When i click radio button for another question, the radio button from previous question become not chosen just like the question left blank.

Is it possible to make radio buttons not dissapear from previous/another question when the other question's radio button is clicked?

//data.json

[{
  "surveyid": 101,
  "surveyname": "Vitamin",
  "createdby": "Dr. Sarah",
  "createddate": "16-01-2018",
  "question": [{
      "questionid": 1,
      "questiondesc": "Q-1?",
      "qno": 1,
      "alloptions": [{
          "options": "A",
          "answer": "Yes"
        },
        {
          "options": "B",
          "answer": "No"
        }
      ]
    },

    {
      "questionid": 2,
      "questiondesc": "Q_2?",
      "qno": 2,
      "alloptions": [{
          "options": "A",
          "answer": "Yes"
        },
        {
          "options": "B",
          "answer": "No"
        },
        {
          "options": "C",
          "answer": "Don't know"
        }
      ]
    },

    {
      "questionid": 3,
      "questiondesc": "Q_3",
      "qno": 1,
      "alloptions": [{
          "options": "A",
          "answer": "Yes"
        },
        {
          "options": "B",
          "answer": "No"
        }
      ]
    }
  ]
}]
<div *ngIf="isVerified" align="left" class="container">
  <div *ngFor="let items of jsonData">
    <div *ngFor="let items2 of items.question">
      <label>{{items2.questionid}}. {{items2.questiondesc}}</label>
      <div *ngFor="let items3 of items2.alloptions">
        <div class="radio" class="form-control second-form">
          <input type="radio" name="formValue" value="{{items3.answer}}"><b>{{items3.options}}</b>. {{items3.answer}}
        </div>
      </div><br>
    </div>
  </div>
  <div align="center">
    <button class="btn btn-sm btn-success">Submit</button>
  </div>
</div>

Upvotes: 1

Views: 2220

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58543

Issue is because of same name for all the radio inputs :

name="formValue"

You should name different for the other radio button group.


Solution :

name="formValue{{items2.questionid}}"

Upvotes: 3

Related Questions