问题
I have a list of questions as given below.
public questionList = [
{
question:{
id: "Q1",
query:"query 1"
},
options:[
{
id: "opt1",
text: "Q1_opt1"
},
{
id: "opt2",
text: "Q1_opt2"
}
],
selected:{
id:"",
text:""
}
},
{
question:{
id: "Q2",
query:"query 2"
},
options:[
{
id: "opt1",
text: "Q2_opt1"
},
{
id: "opt2",
text: "Q2_opt2"
}
],
selected:{
id:"",
text:""
}
}
];
My intention is to list the questions along with options as radio buttons. Whenever somebody selects an option, the id of the selected option should be assigned to "selected.id" which is associated with that question.
Following is the HTML part.
<div *ngFor="let question of questionList">
{{question.question.query}}
<br>
<div *ngFor="let option of question.options">
<input type="radio" value="{{option.id}}" [(ngModel)]="question.selected.id">{{option.text}}
<br>
</div>
{{question.selected | json}}
<br>
<br>
</div>
But when i select the any option for the first question, option for the second question is also getting selected and vise versa.
what would have gone wrong here?
回答1:
You are missing name attribute on radio. The Name should be unique for one set of Options.
In your use case where radio buttons are genrated dynamically you can use index of loop to set name
like this -
<div *ngFor="let question of questionList; let i = index">
{{question.question.query}}
<br>
<div *ngFor="let option of question.options; let j = index">
<input type="radio" [value]="option?.id" [(ngModel)]="question.selected.id" [name]='"abc"+i+j'>{{option.text}}
<br>
</div>
{{question.selected | json}}
</div>
Working Example
回答2:
Assign name to the radio button
<div *ngFor="let question of questionList; let i = index">
{{question.question.query}}
<br>
<div *ngFor="let option of question.options">
<input type="radio" [name]= "i" value="{{option.id}}" [(ngModel)]="question.selected.id">{{option.text}}
<br>
</div>
{{question.selected | json}}
<br>
<br>
</div>
回答3:
In your array id is same thats why its selecting the option button of other array.
you can try this
//HTMl code
<div *ngFor="let question of questionList">
{{question.question.query}}
<br>
<div *ngFor="let option of question.options">
<input type="radio" [value]="option" [(ngModel)]="question.selected">{{option.text}}
<br>
</div>
{{question.selected | json}}
<br>
<br>
</div>
来源:https://stackoverflow.com/questions/54035997/handling-radio-buttons-with-angular-6