首页 > 解决方案 > Ionic 3:如何从 RadioButton 中仅获取选定的值?

问题描述

我在一个列表中有多个单选按钮,我只想获取所选单选按钮的值,但我正在获取单击事件的值。

就像我单击选项 1(10 次)然后选择选项 2(1 次)一样,我得到的值类似于 [Option 1, Option 1,Option 1....x10time, Option 2]

我怎样才能做到这一点?

下面是我的代码。

我的 HTML,

<ion-list radio-group [(ngModel)]="sizeDetails">
    <ion-list-header>
      Select Your Preference
    </ion-list-header>

    <ion-item no-lines *ngFor="let list of prices_details; let i = index;">
      <ion-label text-wrap style="font-size:12px; color:black;">
        {{list.size}}
      </ion-label>

      <ion-label fixed text-right style="font-size:12px; color:black;">
        {{list.discounted_price_pretty}}
      </ion-label>
      <ion-radio item-left color="secondary" value="{{list.size}}, {{list.discounted_price_pretty}}"
        (ionSelect)="selectSize(list.size ,list.discounted_price_pretty, $event)">
      </ion-radio>

my.ts 代码,

selectSize(size, discounted_price_pretty, event) {
    if (event.checked) {
      this.selectedSize.push(size);
      this.selectedSizePrice.push(discounted_price_pretty);
    }
    else {
      let sizeindex = this.removeCheckedFromSize(size);
      this.selectedSize.splice(sizeindex, 1);
      let sizeprice = this.removeCheckedFromSizePrice(discounted_price_pretty);
      this.selectedSizePrice.splice(sizeprice, 1);
    }
  }
  //Removes checkbox from array when user uncheck it
  removeCheckedFromSize(size: String) {
    return this.selectedSize.findIndex((sizeType) => {
      return sizeType === size;
    })
  }
  //Removes checkbox from array when you uncheck it
  removeCheckedFromSizePrice(discounted_price_pretty: String) {
    return this.selectedSizePrice.findIndex((sizeprice) => {
      return sizeprice === discounted_price_pretty;
    })
  }

标签: ionic-frameworkionic3

解决方案


首先,我不认为selectSize函数需要那么大。我建议您在编写代码时应用单一职责原则。

其次,如果这是一个表单,我建议您使用Form Groups。但是,如果您选择坚持您的方法,这绝对没问题,您可能希望您的代码$event在提交时简单地获取值。

eventTS 文件函数中的参数value将从ion-radioHTML 元素返回参数。


推荐阅读