[英]How can I disable the button click in my Ionic 3 Angular app until the toast message gets dismissed?
目前,我正在使用一個按鈕來顯示吐司中的一些信息。 單擊按鈕時,烤面包機將顯示該消息。 當前,吐司持續時間設置為2秒。 吐司啟動時,我需要在2秒鍾內禁用按鈕單擊,如果它消失了,則按鈕可以再次單擊。 即,在吐司消息消失之前,我們不應該單擊該按鈕。
這是我的實現:
在我的HTML中:
<button ion-button class="my-button" type="button" full (click)="message()">
Click Me
</button>
在我的ts文件中:
message() {
this.message.alert('Hi Welcome');
}
我在消息服務中使用Toast控制器,如下所示:
export class MessageService {
constructor(public toastCtrl: ToastController) {}
private toast(message: string) {
const toast = this.toastCtrl.create({
message: message,
duration: 2000
});
toast.present();
}
error (message: string) {
this.toast(message);
}
info(message: string) {
this.toast(message);
}
warning(message: string) {
this.toast(message);
}
alert (message: string) {
this.toast(message);
}
}
我實際上已經實現了吐司功能,但是我不知道如何暫時禁用按鈕單擊2秒鍾。
您可以使用設置為true
的boolean variable
2秒鍾:
toastOpen: boolean = false;
private toast(message: string) {
const toast = this.toastCtrl.create({
message: message,
duration: 2000
});
toast.present();
this.toastOpen = true;
// reset after 2 seconds
setTimeout(() => {
this.toastOpen = false;
}, 2000);
// alternative solution proposed by troy-myers:
// toast.onDidDismiss(() => { this.toastOpen = false; }); }
使用此變量來禁用您的按鈕:
<button ion-button class="my-button" type="button" full (click)="message()" [disabled]="toastOpen">
Click Me
</button>
編輯:如果您還想阻止點擊操作,請完全添加:
message() {
if(!this.toastOpen) {
this.message.alert('Hi Welcome');
}
}
您可以修改服務以返回Toast
的實例,如下所示:
import { Toast } from 'ionic-angular';
export class MessageService {
constructor(public toastCtrl: ToastController) {}
private toast(message: string): Toast {
const toast = this.toastCtrl.create({
message: message,
duration: 2000
});
return toast;
}
error (message: string): Toast {
return this.toast(message);
}
info(message: string): Toast {
return this.toast(message);
}
warning(message: string): Toast {
return this.toast(message);
}
alert (message: string): Toast {
return this.toast(message);
}
}
然后在您的頁面中創建一個新屬性,以了解何時應啟用/禁用按鈕,並像下面這樣修改message
方法:
public isDisabled: boolean = false;
// ...
message() {
// Disable the button
this.isDisabled = true;
const toast = this.message.alert('Hi Welcome');
toast.onDidDismiss(() => {
// Enable the button when the toast is dismissed
this.isDisabled = false;
});
// Show the toast
toast.present();
}
然后在按鈕中使用該屬性:
<button [disabled]="isDisabled" ion-button class="my-button" type="button" full (click)="message()">
Click Me
</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.