简体   繁体   English

如何在 *ngFor 中放置单选按钮逻辑?

[英]How to put radio button logic in *ngFor?

i have options populated in the form with radio buttons now when i select one of the option i dont see isChecked true , am i missing anything below using angular ?我现在在表单中填充了带有单选按钮的选项,当我选择我没有看到的选项之一isChecked true 时,我是否缺少下面使用 angular 的任何内容?

app.component.html应用程序组件.html

<div class="form-group">
 <label>answerOption</label>
    <div *ngFor="let option of singleQuestion.answerOption">
        <label>
           <input type="radio" name="option.isChecked" 
              [value]="true" (change) ="handleChange(option.isChecked)">
                 {{option.answerText}}
        </label>
   </div>

First you need the group the radio button and this is done by providing the same name for the radio buttons.首先,您需要将单选按钮分组,这是通过为单选按钮提供相同名称来完成的。

example:-例子:-

<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

So when the user can check only one option at a time.因此,当用户一次只能选择一个选项时。

For your example, I have given name has question.对于你的例子,我已经给出了名字有问题。

We need to understand which option is selected by user, so you need bind a unique value, in my above given gender example, I have added different value for each radio control value.我们需要了解用户选择了哪个选项,因此您需要绑定一个唯一值,在我上面给出的性别示例中,我为每个无线电控制值添加了不同的值。

 [value]="option.answerOptionId"

Here, [value] is one way binding, from code to view therefore the ischecked it not set to true.这里,[value] 是一种绑定方式,从代码到视图,因此 ischecked 它没有设置为 true。 Better way is given below.下面给出了更好的方法。

       <div class="form-group">
          <label>answerOption</label>
            <div *ngFor="let option of singleQuestion">
                <label>
                <input type="radio" name="question" 
         [value]="option.answerOptionId" (change) ="handleChange(option)">
                {{option.answerText}}
                </label>
            </div>
        </div>

The best thing i can choose from your option is option.answerOptionId, refer my above html snippet.我可以从你的选项中选择的最好的东西是 option.answerOptionId,参考我上面的 html 片段。 Sending the current radio button, option.isChecked is not correct, since we will always get false.发送当前单选按钮 option.isChecked 是不正确的,因为我们总是会得到 false。 Reason you have provided the value false for both the answer option in ts file.您为 ts 文件中的答案选项提供值 false 的原因。 For the event I have sent whole radio control.对于这个事件,我已经发送了整个无线电控制。 Log method in ts file will show you the current option selected by user. ts 文件中的日志方法将显示用户选择的当前选项。

To sum up.总结。

  • Same name for radio button.单选按钮的同名。
  • Provide different value for each radio button.为每个单选按钮提供不同的值。
  • Send the control or the control value in the event, whichever is favorable.发送事件中的控件或控件值,以有利者为准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM