如何以反应形式获得无线电的选定值 [英] how to get selected value of radio in reactive form
问题描述
我正在尝试获取单选按钮的 selectedValue 并将其与单选文本一起传递为 true.如果选择了选项 1,则 selectedValue 将作为真发送,否则为假.如果选择了选项 2,则 selectedValue 将被发送为 true,否则为 false.我无法将其设置为 true.想知道以前是否有人这样做过?
https://stackblitz.com/edit/angular-xfrezb
首先,始终将相关代码作为代码块包含在您的问题中,因为链接会随着时间的推移而消失...
但至于你的问题,由于你正在处理几个问题和动态value
,我会传递当前的formArray components
和当前的answer代码>.您需要首先将所有表单控件
selectedValue
设置为 false
,否则切换单选按钮每个最终都会变成 true
点击每个他们.因此,在首先将所有设置为 false
之后,只需将所选单选按钮设置为 true
.所以做这样的事情:
<p>{{ question.controls.label.value }}</p><div formArrayName="组件"><div *ngFor="let answer of question.controls.component.controls;让 j = 索引" [formGroupName]="j"><标签><input type="radio" name="radio-stacked"(click)="updateSelection(question.controls.component.controls, answer)"><span>{{ answer.value.value }}</span>标签>
然后你的 updateSelection
方法:
updateSelection(formArr, answer) {formArr.forEach(x => {x.controls.selectedValue.setValue(false);});answer.controls.selectedValue.setValue(true);}
你的分叉 StackBlitz
PS,你当然可以考虑做的,不是在你的表单对象中有所有选项,而只是添加你选择的单选按钮的值.
I am trying to get the selectedValue of the radio button and pass it as true with the radio text. selectedValue to be sent as true if Choice 1 is selected else false. And selectedValue to be sent as true if Choice 2 is selected, else false. I could not set it to true. Was wondering if anyone has done this before?
https://stackblitz.com/edit/angular-xfrezb
First of all, always include the relevant code in your question as code blocks, since links tend to die over time...
But as for your question, since you are dealing with several questions and dynamic value
, I would pass the current formArray components
and the current answer
. You would need to first then set all form controls selectedValue
as false
, since otherwise toggling the radio buttons each would eventually become true
of clicking every of them. So after first setting all as false
then just set the chosen radio button as true
. So do something like this:
<div *ngIf="question.controls.type.value === 'radio'">
<p>{{ question.controls.label.value }}</p>
<div formArrayName="component">
<div *ngFor="let answer of question.controls.component.controls;
let j = index" [formGroupName]="j">
<label>
<input type="radio" name="radio-stacked"
(click)="updateSelection(question.controls.component.controls, answer)">
<span>{{ answer.value.value }}</span>
</label>
</div>
</div>
</div>
Then your updateSelection
method:
updateSelection(formArr, answer) {
formArr.forEach(x => {
x.controls.selectedValue.setValue(false);
});
answer.controls.selectedValue.setValue(true);
}
Your forked StackBlitz
PS, what you could of course consider doing, is not to have all choices in your form object, but just add the value of the radio button you have chosen.
这篇关于如何以反应形式获得无线电的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!