Close Modal in Ionic 4 by Back Button

后端 未结 6 2009
名媛妹妹
名媛妹妹 2021-02-03 12:38

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 bac

6条回答
  •  佛祖请我去吃肉
    2021-02-03 13:18

    You can use the registerBackButtonAction method that Platform service contains. This method allows override the default native action of the hardware back button. The method accepts a callback function as parameter where you can implement your logic. In summary you should do the following:

    • Inject the Platform service inside the Foo component.
    • Call the registerBackButtonAction in the ngOnInit (or another init method) and pass a function callback as parameter that executes the logic to close the modal (this.modalController.dismiss();)
    • Clear the action when the modal component is closed (for example in ngOnDestroy method). To do that, the registerBackButtonAction returns a function that when is called the action is removed.

    The code should be something like:

    constructor(private platform: Platform) {
        ...
    }
    
    ngOnInit() {
        this.unregisterBackAction = this.platform.registerBackButtonAction(() => {
            this.modalController.dismiss();
        })
    }
    
    ngOnDestroy() {
        if(this.unregisterBackAction) this.unregisterBackAction();
    }
    

提交回复
热议问题