dilluns, 22 de maig del 2017

Ionic 2. Adding a popover menu


Maybe you want add new features on your app, if this is not an action which it affect only one thing such as realize a backup or restore it, print a summary, etc... for this, a popover is a good option to contain these actions. 

A popover is a dialog that typically appears above other content on the screen and it usually it is positioned at top of the current page, and displays actions that can be carried out. As almost everything in Ionic it is really easy, another thing is as implement these actions. Here you can find more info.

A possible popover could look like to this


Well,  for implement a popover, Ionic provides a PopoverController that we use it for creating, present and dismiss these dialog.

For that we need a template and a controller, I separate it in two files a popover.html for the template and a popover.ts for the controller and I save it in the same directory which contains the page on it appears. It is my way of doing it, but not the unique.

The template can be like this 

<ion-list> <ion-list-header color="primary">Options</ion-list-header> <button ion-item (tap)="backup()">Backup</button> <button ion-item (tap)="restore()">Restore backup</button> </ion-list>

As you see it's just a list

The popover controller looks like

import { Component } from '@angular/core'; import { ViewController, NavParams } from 'ionic-angular'; @Component({ templateUrl: 'popover.html' }) export class PopoverHomePage constructor (public viewCtrl: ViewController, public navParams: NavParams) { } backup() { let data = this.navParams.get('data'); save(data); this.viewCtrl.dismiss(); } restoreBackup() { let data = this.navParams.get('data'); restore(data); this.viewCtrl.dismiss(); } }

And now inside the template where the popover will be showed, in the toolbar section we put a button and at the method which will present the popover we passed him the $event. That variable, contains the original browser event object.

<ion-header> <ion-toolbar color="primary"> <ion-title>eDomestic</ion-title> <ion-buttons right> <button ion-button icon-only color="royal" (tap)="optionsPopover($event)"> <ion-icon name="more"></ion-icon> </button> </ion-buttons> </ion-toolbar> </ion-header>


Inside the controller we put the method which respond to the click button event.

//Show popover menu optionsPopover(event) { let popover = this.popoverCtrl.create(PopoverHomePage, {page: this.pageContent}) popover.present({ ev: event }); }

And in the controller we import PopoverController from ionic-angular. 

First parameter is the component and the second the data that we pass to the popover. Finally we add the popover component in the app.module.ts file and it is ready for work .

And that it's all our popover is ready to be showed.

1 comentari: