如何设置Ionic 2中单选按钮警报的值
问题描述:
我有包含12个以上选项的单选按钮警报,我想检查与我的变量值相等的选项。如何设置Ionic 2中单选按钮警报的值
我用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();
}
您能否将代码添加到帖子中? – sebaferreras
@sebaferreras是的,我做了..我把我的长途检查单选按钮的警报,但希望有一个简短的方法来帮助我,如果我有超过10或12个单选按钮 –
谢谢,请看看我的回答:) – sebaferreras