How to close Ionic modals using the hardware back button

Disclaimer

Angular

import {Component} from '@angular/core';
import {ModalController} from '@ionic/angular';
@Component({
templateUrl: 'my-modal.html',
styleUrls: ['./my-modal.scss'],
selector: 'app-my-modal'
})
export class MyModal {
constructor(private modalController: ModalController) {} @HostListener('document:ionBackButton', ['$event'])
private async overrideHardwareBackAction($event: any) {
await this.modalController.dismiss();
}
}

StencilJS

import {Component, Element, Listen} from '@stencil/core';

@Component({
tag: 'app-my-modal',
styleUrl: 'app-my-modal.scss'
})
export class AppMyModal {
@Element() el: HTMLElement;

async componentDidLoad() {
history.pushState({modal: true}, null);
}

@Listen('window:popstate')
async handleHardwareBackbutton(_e: PopStateEvent) {
await this.closeModal();
}

async closeModal() {
await (this.el.closest('ion-modal')
as HTMLIonModalElement).dismiss();
}

render() {
return [
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button
onClick={() => this.closeModal()}>
<ion-icon name="close"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>,

<ion-content padding>
<h1>Yolo</h1>
</ion-content>
];
}
}

Stencil One

@Listen('popstate', { target: 'window' })

Cherry on the cake 🍒🎂

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store