Modals are used in webpage very much nowadays. Modals are a very easy way to present some options or show data very nicely. In Ionic, modals are just regular pages that get called with a ModalController.When modal is dismissed all data are destroyed inside modal page.
So lets start how to create a modal in ionic 2 application?
First create a modal page using a command.
$ ionic g page MyModal
Next import the new page mymodal in the app module(app.module.ts) and in the page from which the modal will be called. Also add it to the declarations and entryComponents of the app module. Here’s an example of what your app module should look like:
import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { MyModal } from '../pages/mymodal/mymodal'; @NgModule({ declarations: [ MyApp, HomePage, MyModal ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, MyModal ], providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}] }) export class AppModule {}
Then in the template for the page that calls the modal, we’ll just add a button to show the modal in home.html.
<button ion-button (click)="modalshow()">Show Modal</button>
Import and inject ModalController and define the modalshow method that gets called when click on the button.
import { Component } from '@angular/core'; import { ModalController } from 'ionic-angular'; import { MyModal } from '../pages/mymodal/mymodal'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public modalCtrl: ModalController) { } modalshow() { let myModal = this.modalCtrl.create(MyModal); myModal.present(); } }
Now if we want to dismiss the modal
Then add button in mymodal.html
<button ion-button (click)="modalhide()">Close Modal</button>
Now implement the modalhide method in the modal’s page(mymodal.ts) class definition:
import { Component } from '@angular/core'; import { ViewController } from 'ionic-angular'; @Component({ selector: 'page-mymodal', templateUrl: 'mymodal.html' }) export class MyModal { constructor(public viewCtrl: ViewController) {} modalhide() { this.viewCtrl.dismiss(); } }
That’s all.
Hi All im rookie here. Good post! Thx! Love your stories!