如何禁用我的 Ionic 3 Angular 应用程序中的按钮单击,直到 toast 消息被取消?

How can I disable the button click in my Ionic 3 Angular app until the toast message gets dismissed?

目前我正在使用一个按钮在 toast 中显示一些信息。单击按钮时,吐司将显示消息。目前,吐司持续时间设置为 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);
  }
}

我其实已经实现了toast,但是我不知道如何暂时禁用按钮点击2秒。

您可以使用设置为 trueboolean 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');
    }
} 

您可以将服务修改为 return 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);
  }
}

然后在您的页面中创建一个新的 属性 以了解按钮何时应该 enabled/disabled 并像这样修改 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>