我有包含超过 12 个选项的单选按钮警报,我想检查等于我的变量值的选项。
我使用 if 语句以少于 4 个选项来完成这件事。但现在我有超过 12 个选项,所以我希望有更简单的方法来检查我的变量的值并选择相等的选项。
---编辑---
这是我的html的一部分
<button ion-button clear full (click)="selectColor(x.color)">{{x.color}}</button>
.ts 功能(我想要一个更好的方法来选择警报的单选按钮(如果有的话))
selectColor(color){
let alert1 = this.alertCtrl.create();
alert1.setTitle('Color Theme');
if(color=="red"){
alert1.addInput({
type: 'radio',
label: 'Red',
value: 'red',
checked: true
});
}else{
alert1.addInput({
type: 'radio',
label: 'Red',
value: 'red',
});
}
if(color=="pink"){
alert1.addInput({
type: 'radio',
label: 'Pink',
value: 'pink',
checked: true
});
}else{
alert1.addInput({
type: 'radio',
label: 'Pink',
value: 'pink'
});
}
if(color=="purple"){
alert1.addInput({
type: 'radio',
label: 'Purple',
value: 'purple',
checked: true
});
}else{
alert1.addInput({
type: 'radio',
label: 'Purple',
value: 'purple'
});
}
if(color=="blue"){
alert1.addInput({
type: 'radio',
label: 'Blue',
value: 'blue',
checked: true
});
}else{
alert1.addInput({
type: 'radio',
label: 'Blue',
value: 'blue'
});
}
...
alert1.addButton('Cancel');
alert1.addButton({
text: 'Okay',
handler: data => {
...
}
});
alert1.present();
}
最佳答案
是的,有一种简单的方法可以做到这一点。您可以像这样在 checked
属性中添加条件:
selectColor(color){
let alert1 = this.alertCtrl.create();
alert1.setTitle('Color Theme');
alert1.addInput({
type: 'radio',
label: 'Red',
value: 'red',
checked: color === "red"
});
alert1.addInput({
type: 'radio',
label: 'Pink',
value: 'pink',
checked: color === "pink"
});
alert1.addInput({
type: 'radio',
label: 'Purple',
value: 'purple',
checked: color === "purple"
});
alert1.addInput({
type: 'radio',
label: 'Blue',
value: 'blue',
checked: color === "blue"
});
// ...
alert1.addButton('Cancel');
alert1.addButton({
text: 'Okay',
handler: data => {
// ...
}
});
alert1.present();
}
编辑
还有一种添加所有颜色的更好方法,即使用 forEach
循环和包含所有颜色的数组:
selectColor(color){
let alert1 = this.alertCtrl.create();
alert1.setTitle('Color Theme');
// Add the new colors here!
const colors = ['Red', 'Pink', 'Purple', 'Blue'];
colors.forEach(color => {
alert1.addInput({
type: 'radio',
label: color,
value: color.toLowerCase(),
checked: color === color.toLowerCase()
});
});
// ...
alert1.addButton('Cancel');
alert1.addButton({
text: 'Okay',
handler: data => {
// ...
}
});
alert1.present();
}
关于angular - 如何在 Ionic 2 中设置单选按钮警报的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250775/