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?
EDIT: More details:
I have a button that opens my modal:
async onClick() {
const modal = await this.modalController.create({
component: Foo,
});
return await modal.present();
}
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.
Passing data to an Ionic modal This is as simple as calling the componentProps on our modalController create function. number: number = 3; const modal = await this. modalController.
Hardware Back Button in Capacitor and CordovaThe @capacitor/app package must be installed in Capacitor apps to use the hardware back button. When running in a Capacitor or Cordova application, Ionic Framework will emit an ionBackButton event when a user presses the hardware back button.
Enol's answer helped me find a solution, thanks for that.
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();
}
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:
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();
)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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With