[英]How to add a disabled button to ionic 2 alert
I created an ionic2 alert and I have to disable a button according to a condition. 我创建了一个ionic2警报,我必须根据条件禁用按钮。
This is a simple structure of my code: 这是我的代码的简单结构:
import { AlertController } from 'ionic-angular';
export class MyPage {
constructor(public alertCtrl: AlertController) {
}
showCheckbox(condition) {
let alert = this.alertCtrl.create();
alert.setTitle('Which planets have you visited?');
alert.addInput({
type: 'checkbox',
label: 'Alderaan',
value: 'value1',
checked: true
});
alert.addInput({
type: 'checkbox',
label: 'Bespin',
value: 'value2'
});
alert.addButton('Cancel');
alert.addButton({
text: 'Okay',
handler: data => {
console.log('Checkbox data:', data);
this.testCheckboxOpen = false;
this.testCheckboxResult = data;
}
});
alert.present();
}
}
I have to disable Okay
button if given condition is true
(parameter 'condition' that passed to the showCheckbox()
function). 如果给定条件为
true
我必须禁用Okay
按钮(传递给showCheckbox()
函数的参数'condition')。
I know the question was asked over a year ago, just in case someone other needs it. 我知道这个问题是在一年前提出的,以防其他人需要它。
I've created a little, I would say, "workaround", which works like a charm. 我创造了一点,我会说,“解决方法”,它就像一个魅力。
alert.present()
offers a Promise
, so we can listen to it, after the alert was successfully created. alert.present()
提供了一个Promise
,因此我们可以在成功创建警报后收听它。
Now, here's what I've done: 现在,这就是我所做的:
alert.present().then(() => {
/** disable the confirm button initial */
document.querySelector('ion-alert div.alert-button-group button:nth-of-type(2)').setAttribute('disabled', 'true');
return;
});
It's a bit hacky to access the confirm button via document.querySelector();
通过
document.querySelector();
访问确认按钮有点麻烦document.querySelector();
and the above query, but the confirm button does not has a unique identifier as I've seen it, something like role="confirm"
or so. 和上面的查询,但确认按钮没有我见过的唯一标识符,类似于
role="confirm"
。
So You need to write a function, which will be triggered on each click on Your inputs (via handler
). 因此,您需要编写一个函数,该函数将在每次单击您的输入时触发(通过
handler
)。
alert.addInput({
type: 'checkbox',
label: 'testLabel',
value: 'testValue',
handler: () => {
functionToCheckConfirmButtonState();
}
});
There You need to check Your checkbox values inside the functionToCheckConfirmButtonState();
你需要在
functionToCheckConfirmButtonState();
检查你的复选框值functionToCheckConfirmButtonState();
function and enable the confirm button with: 功能并启用确认按钮:
document.querySelector('ion-alert div.alert-button-group button:nth-of-type(2)').removeAttribute('disabled');
or disable it again with: 或者再次禁用它:
document.querySelector('ion-alert div.alert-button-group button:nth-of-type(2)').setAttribute('disabled', 'true');
Hope I could help. 希望我能提供帮助。
Cheers Unkn0wn0x 干杯Unkn0wn0x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.