Search code examples
angulartypescriptionic2ionic3

Ionic 2: Modal doesn't close when clicking on backdrop


I'm trying to run a simple example app with a modal that covers only the lower part of the screen. I want the modal to close when I click on the backdrop which I think is expected behavior. However, nothing happens when clicking the backdrop. I know about enableBackdropDismiss which should be true by default. I'm using Ionic-angular 3.2.1.

Homepage:

import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { Modal } from '../modal/modal';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public modalCtrl: ModalController) {

  }

  openModal(){
    let modal = this.modalCtrl.create(Modal);
    modal.present();
  }

}
<ion-header>
  <ion-navbar>
    <ion-title>
      Modal Test
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="openModal()">Open Modal</button>
</ion-content>

Modal:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-modal',
  templateUrl: 'modal.html',
})
export class Modal {

  constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) {
  }

  closeModal(): void {
    this.viewCtrl.dismiss();
  }

}
<ion-footer>
    <ion-navbar>
        <h4>Modal</h4>
        <p>I'm a Modal</p>
        <button ion-button (click)="closeModal()">Close Modal</button>
    </ion-navbar>
</ion-footer>

This is what it looks like when the modal is shown. The modal only closes when clicking the button, not when clicking the background:

enter image description here


Solution

  • Just like we figured out in the comments, one way to solve this would be to add an empty content to the modal, binding the click event of the content to the closeModal method, and then setting the background of the content to be transparent

    <ion-content tappable (click)="closeModal()">
    </ion-content>
    <ion-footer>
        <ion-navbar>
            <h4>Modal</h4>
            <p>I'm a Modal</p>
            <button ion-button (click)="closeModal()">Close Modal</button>
        </ion-navbar>
    </ion-footer>
    

    And in the component styles:

    ion-content div.scroll-content {
        background-color: transparent;
    }