ngFor 单选按钮无法取消选择
我正在尝试做一个测验。我可以按照我想要的方式显示问题和答案,但单选按钮无法正常工作。一旦单击,它们就不会变得未被标记,无论是再次单击它们还是单击另一个。它们确实传递了最后单击的值,但您无法重新单击已单击的值。 (即,您单击答案 1,然后单击 3,然后再次单击 1。1 和 3 均被标记,但传递 3 的值)
const quizQuestions = [
{
index: 0,
formName: "q0",
question: "Ready?",
options: [
{
option: "1",
answer: "Begin!",
affectUp: [],
affectDown: []
}
]
},
{
index: 1,
formName: "q1",
question: "You\u2019re a “jack-of-all-trades”.",
options: [
{
option: "1",
answer: "Strongly Agree"
},
{
option: "2",
answer: "Neutral"
},
{
option: "3",
answer: "Strongly Disagree"
}
]
<div *ngFor="let qz of quizQuestions; let i = index;">
<div class="card" *ngIf="i === quizNumber">
{{qz.question}}
<div class="card-body">
<div *ngFor="let opt of qz.options; let i2 = index;">
<form [formGroup]="quizForm">
<label for="o-{{i}}-{{i2}}">{{opt.answer}}</label>
<input type="radio" id="o-{{i}}-{{i2}}" formControlName="q{{i}}" [value]="opt.option">
</form>
</div>
</div>
</div>
</div>
ngOnInit(): void {
this.quizForm = this.formbuilder.group(
{
q0: [''],
q1: [''],
q2:[''],
q3: [''],
q4: ['']
}
)
}
I'm trying to make a quiz. I am able to make the questions and answers appear the way I want, but the radio buttons aren't working correctly. Once clicked, they do not become unmarked, either by clicking them again or clicking another one. They do pass the value of the last one that was clicked, but you can't reclick one that was already clicked. (ie. you click answer 1, then 3, then 1 again. both 1 and 3 are marked but the value of 3 is passed)
const quizQuestions = [
{
index: 0,
formName: "q0",
question: "Ready?",
options: [
{
option: "1",
answer: "Begin!",
affectUp: [],
affectDown: []
}
]
},
{
index: 1,
formName: "q1",
question: "You\u2019re a “jack-of-all-trades”.",
options: [
{
option: "1",
answer: "Strongly Agree"
},
{
option: "2",
answer: "Neutral"
},
{
option: "3",
answer: "Strongly Disagree"
}
]
<div *ngFor="let qz of quizQuestions; let i = index;">
<div class="card" *ngIf="i === quizNumber">
{{qz.question}}
<div class="card-body">
<div *ngFor="let opt of qz.options; let i2 = index;">
<form [formGroup]="quizForm">
<label for="o-{{i}}-{{i2}}">{{opt.answer}}</label>
<input type="radio" id="o-{{i}}-{{i2}}" formControlName="q{{i}}" [value]="opt.option">
</form>
</div>
</div>
</div>
</div>
ngOnInit(): void {
this.quizForm = this.formbuilder.group(
{
q0: [''],
q1: [''],
q2:[''],
q3: [''],
q4: ['']
}
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将创建尽可能多的
将
You're creating as many
<form>
s as you have options because you're placing it inside your*ngFor
. Also, radio buttons need to all have the samename
in order for the browser to regard them as part of the same set of options.Take the
<form>
out of the*ngFor
iterations and give all related radio buttons the samename
attribute.