通过“后退"按钮在Ionic 4中关闭模态 [英] Close Modal in Ionic 4 by Back Button

查看:283
本文介绍了通过“后退"按钮在Ionic 4中关闭模态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ionic 4 中有一个 Modal .当用户按下手机上的后退按钮(或浏览器中的后退按钮)时,我想关闭.

I have a Modal in Ionic 4. I'd like to close it, when a user press the back button on her mobile (or the back button in her browser).

有人知道我该怎么做吗?

Does anyone know how I can do this?

更多详细信息:

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

I have a button that opens my modal:

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

组件Foo的内容并不多于关闭模式的按钮:this.modalController.dismiss();.到目前为止一切顺利.

Component Foo doesn't have much more content than a button that closes the modal: this.modalController.dismiss();. So far so good.

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

On my mobile, however, the app now closes when the modal is open and the user taps the mobile's back button. But in this case only the modal should close.

推荐答案

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

Enol's answer helped me find a solution, thanks for that.

platform.registerBackButtonAction在v4中不再存在.我改用platform.backButton.subscribe,但是没有用.这是可行的:

platform.registerBackButtonAction does no longer exist in v4. I tried platform.backButton.subscribe instead, but it didn't work. What works is this:

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();
}

这篇关于通过“后退"按钮在Ionic 4中关闭模态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆