![](/img/trans.png)
[英]How to change radio button value in the multiple radio button group dynamically in ionic 4 after getting the value from API?
[英]How to set the value of radio button alert in Ionic 2
我有單選按鈕警報,包含超過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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.