Issue
I am designing a feedback page where, There are multiple questions are being asked and all the questions have same multiple choice answers. So I have designed like below.
options: string[] = ['Excellent', 'Fair', 'Good', 'Poor'];
questions: any = [
{
question: "How would you rate A",
answer: this.options,
radioSelected: ""
},
{
question: "How would you rate B",
answer: this.options,
radioSelected: ""
},
{
question: "How would you rate C",
answer: this.options,
radioSelected: ""
},
{
question: "How would you rate D",
answer: this.options,
radioSelected: ""
},
{
question: "How would you rate E",
answer: this.options,
radioSelected: ""
}
];
<div *ngFor="let q of questions; index as i">
<label id="example-radio-group-label">{{q.question}}</label>
<div class="row">
<div class="form-check" *ngFor="let option of q.answer">
<div class="col-md-3">
<input class="form-check-input" id="{{option}}" [value]="option" type="radio" name="options"
[(ngModel)]="q.radioSelected">
<label class="form-check-label" for="{{option}}">
{{option}}
</label>
</div>
</div>
</div>
<hr>
</div>
The code is displaying fine in the UI. But When I click on the radio button for any question, Only first question's options are getting selected. I am new to angular, Kindly help me how to solve this.
Solution
You are missing unique name attribute on radio. The Name should be unique for one set of Options.
In your use case where radio buttons are generated dynamically you can use index of loop to set name like this -
<div *ngFor="let q of questions; let questionIndex=index">
<label id="example-radio-group-label">{{q.question}}</label>
<div class="row">
<div class="form-check" *ngFor="let option of q.answer; let answerIndex=index">
<div class="col-md-3">
<input class="form-check-input" [value]="option" type="radio" name="options{{questionIndex}}{{answerIndex}}"
[(ngModel)]="q.radioSelected">
<label class="form-check-label">
{{option}}
</label>
</div>
</div>
</div>
<hr>
</div>
Please check working example here.
Similar question here and here.
Hope this will help you !!
Answered By - Santosh Shinde
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.