ionic-framework - 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;
})
}
解决方案
首先,我不认为selectSize
函数需要那么大。我建议您在编写代码时应用单一职责原则。
其次,如果这是一个表单,我建议您使用Form Groups。但是,如果您选择坚持您的方法,这绝对没问题,您可能希望您的代码$event
在提交时简单地获取值。
event
TS 文件函数中的参数value
将从ion-radio
HTML 元素返回参数。
推荐阅读
- typescript - 泛型类型断言(TypeScript Advanced)
- java - Spring 安全性:跳过 antMatches
- html - React.Js/Typescript:如何通过道具传递颜色?
- ruby-on-rails - 无论我尝试什么都无法访问 ActionController::Parameters
- python - Matplotlib 版本 1.5.3 与 2.2.2 在极轴上显示
- r - 将 .rda 分配给一个对象并在 R 中的该对象中使用 predict
- c# - 从完整的文本字符串中获取用户名
- powershell - 如何在我的 Web 应用程序中生成访问令牌以与 Exchange Online Powershell 模块一起使用?
- python - 如何以及在哪里获取 json 和 pem 文件以远程连接到内核?
- python - 检查Python DataFrame中的任何值是否为0