How to close Ionic modals using the hardware back button



import {Component} from '@angular/core';
import {ModalController} from '@ionic/angular';
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();


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

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

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

async handleHardwareBackbutton(_e: PopStateEvent) {
await this.closeModal();

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

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

<ion-content padding>

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