首页 > 解决方案 > 通过后退按钮关闭 Ionic 4 中的模态

问题描述

我在Ionic 4中有一个模态。当用户按下她手机上的后退按钮(或浏览器中的后退按钮),我想关闭它。

有谁知道我该怎么做?

编辑:更多细节:

我有一个按钮可以打开我的模式:

async onClick() {
  const modal = await this.modalController.create({
    component: Foo,
  });
  return await modal.present();
}

组件Foo没有比关闭模式的按钮更多的内容:this.modalController.dismiss();. 到目前为止,一切都很好。

然而,在我的手机上,当模式打开并且用户点击手机的后退按钮时,应用程序现在关闭。但在这种情况下,只有模式应该关闭。

标签: modal-dialogionic4

解决方案


Enol 的回答帮助我找到了解决方案,谢谢。

platform.registerBackButtonAction在 v4 中不再存在。我尝试platform.backButton.subscribe了,但没有奏效。有效的是:

private backbuttonSubscription: Subscription;

constructor(private modalCtrl: ModalController) {

ngOnInit() {
    const event = fromEvent(document, 'backbutton');
    this.backbuttonSubscription = event.subscribe(async () => {
        const modal = await this.modalCtrl.getTop();
        if (modal) {
            modal.dismiss();
        }
    });
}

ngOnDestroy() {
    this.backbuttonSubscription.unsubscribe();
}

推荐阅读