【问题标题】:Angular 8: How to get selected data from Dynamic radio buttonAngular 8:如何从动态单选按钮获取选定的数据
【发布时间】:2020-02-03 19:48:29
【问题描述】:

如何从动态单选按钮获取数据(单选按钮是从 json 数据生成的)。单选按钮已成功显示,但我如何从动态单选按钮获取所选数据。

Json 数据示例:

[{Key : color,Values : [{Value : red}]}]

product.component.ts

   <div class="form-group product__option" *ngFor="let item of product.productAttr; let i = index">
                    <label class="product__option-label">{{item.key}}</label>
                    <div class="input-radio-label">
                        <div class="input-radio-label__list">
                            <label *ngFor="let value of item.values; let i = index">
                                <input type="radio" id="{{value.key}}" value="{{value.value}}" name="{{item.key}}" (change)="onItemChange($event)">
                                <span>{{value.value}}</span>
                            </label>
                            
                        </div>
                    </div>
                </div>

【问题讨论】:

标签: angular angular6 angular5 angular7 angular8


【解决方案1】:

您需要在 product.component.ts 文件中实现onItemChange 方法。

onItemChange(value){
   console.log(value);
}

【讨论】:

    【解决方案2】:

    你需要在你的component.ts文件中实现onItemChange方法。

    onItemChange(itemKey, itemValue) { console.log(itemKey + ' ' + itemValue); }

    参考:https://stackblitz.com/edit/angular-ipm7s6?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

    • 好的,但是如何将选定的项目保存在数组中,例如键是颜色,选定的值是红色。当我将所选值更改为蓝色时,数组中的颜色将变为蓝色
    • 只需将新变量 selectedValue 声明为数组,并将您从 @Arunkumar 的函数中获得的数据分配给该数组
    【解决方案3】:

    您需要在动态创建的单选按钮上使用(更改)事件,然后您可以将值传递给它,然后在 ts 文件中使用它。

    例如。

    HTML

     <input class="option" type="radio" value="{{optionsVal.id}}" 
                          id="opt_{{optionsVal.id}}" name="quizOption"
                          (change)="radioFun( optionsVal.id)"
                           />
    

    TS

     radioFun(optionID: any) {
    console.log(optionID)
    }
    

    这样您还可以根据需要在 radioFun 函数上保存并将值推送到任何特定数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多