如何以无功形式获得无线电的选定值 [英] how to get selected value of radio in reactive form

查看:101
本文介绍了如何以无功形式获得无线电的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取单选按钮的selectedValue并将其作为true与单选文本一起传递.如果选择了选择1,则将selectedValue作为true发送,否则为false.如果选择了选择2,则selectedValue将被发送为true,否则为false.我无法将其设置为true.想知道以前是否有人这样做过?

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...

但是关于您的问题,由于您要处理几个问题和动态value,因此我将传递当前的formArray components和当前的answer.您首先需要将所有窗体控件selectedValue设置为false,因为否则切换单选按钮最终将变成单击每个控件的true.因此,在将所有内容都设置为false之后,只需将所选单选按钮设置为true.所以做这样的事情:

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>

然后使用您的updateSelection方法:

updateSelection(formArr, answer) {
  formArr.forEach(x => {
    x.controls.selectedValue.setValue(false);
  });
  answer.controls.selectedValue.setValue(true);
}

您分叉的 StackBlitz

Your forked StackBlitz

您当然可以考虑做的PS,不是在表单对象中具有所有选择,而只需添加您选择的单选按钮的值即可.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆