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

查看:13
本文介绍了通过后退按钮关闭 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天全站免登陆