Set default value for an ion-select-item dynamically - ionic-framework

I'm having some mind blow working with ionic 4, I'm trying to set a default value for an ion-select-option dynamically but I'm not getting the correct behavior
I want to load the data into the ion-select and then assign the first value
HTML
<ion-header>
<ion-toolbar>
<ion-title>home</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div style="height: 30%;"></div>
<ion-item>
<ion-label>UbicaciĆ³n</ion-label>
<ion-select [(ngModel)]="ubicacion" okText="Aceptar" cancelText="Cancelar">
<ion-select-option *ngFor="let ubicacion of ubicaciones">{{ubicacion.nombre}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Fruta</ion-label>
<ion-select [(ngModel)]="selfruits">
<ion-select-option *ngFor="let fruit of fruits" [value]="fruit">{{fruit.name}}</ion-select-option>
</ion-select>
</ion-item>
<div style="height: 25%;"></div>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-button expand="block" (click)="goForward('check-in')">Control</ion-button>
<ion-button expand="block" (click)="goForward('item-list')">Check list</ion-button>
</ion-toolbar>
</ion-footer>
TS
import { Component, OnInit } from '#angular/core';
import { NavController } from '#ionic/angular';
import { Maquina } from 'src/app/model/control/maquina';
import { ControlService } from 'src/app/services/control.service';
import { Ubicacion } from 'src/app/model/control/ubicacion';
import { GeneralService } from 'src/app/services/general.service';
#Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
ubicaciones: Ubicacion[]
ubicacion
constructor(
private navController: NavController,
private controlService: ControlService,
private generalService: GeneralService,
) { }
fruits = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cherry' },
];
selfruits = [this.fruits[1]];
ngOnInit() {
this.fillUbicaciones()
}
fillUbicaciones() {
this.controlService.getUbicaciones().subscribe(x => {
this.ubicaciones = x
console.log("ubicaciones", x)
this.ubicacion = x[1]
})
}
changeUbicacion(value) {
console.log("changeUbicacion", value.detail.value);
// this.ubicacion = this.ubicaciones.find(x => x.nombre == value.detail.value)
}
goForward(action) {
this.generalService.goForward(action)
}
}
This is my data source : https://api.myjson.com/bins/191wsg

You are specifying the second element by using index 1, you should use this.fruits[0] to get the first item in the array.
fruits = [
{ id: 1, name: 'apple' }, // 0
{ id: 2, name: 'banana' }, // 1
{ id: 3, name: 'cherry' }, // 2
];
selfruits = [this.fruits[0]];
You don't need to wrap selFruits in an array, so you can just do:
selFruits = this.fruits[0];

Related

Radio group not working properly when changing the radio group list values frequently in ionic 4

Ionic4 radio group misbehaving while changing the radio group list values dynamically.
Let's take my use case, I have one field country (ion-select) which has a list of countries. Another field called state (ion-radio-group) this will be visible the value based on the country selection. States will be showing fine based on the country selection but the issue is when I click the radio group it will not react in the UI. When I do doubt click the selection will be reflected in the radio group. Why it is not reflected in my first click. Please guide me.
homepage.html
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Home
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}"
[selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="false"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
homepage.ts
import { Component, OnInit} from '#angular/core';
#Component({
selector: 'app-homepage',
templateUrl: './homepage.html',
styleUrls: ['./homepage.scss'],
})
export class homepage implements OnInit {
private pickListValues = {
country: [{
choiceValue: "in",
choice: "India",
child: {
value: [{
choiceValue: "tn",
choice: "Tamilnadu",
child: {
value: []
}
}, {
choiceValue: "dl",
choice: "Delhi",
child: {
value: []
}
}, {
choiceValue: "mi",
choice: "Mumbai",
child: {
value: []
}
}]
}
}, {
choiceValue: "ci",
choice: "China",
child: {
value: [{
choiceValue: "AH",
choice: "Anhui Province",
child: {
value: []
}
}, {
choiceValue: "GX",
choice: "Guangxi Zhuang",
child: {
value: []
}
}]
}
}, {
choiceValue: "jp",
choice: "Japan",
child: {
value: [{
choiceValue: "gu",
choice: "Gunma",
child: {
value: []
}
}, {
choiceValue: "kw",
choice: "Kanagawa",
child: {
value: []
}
}, {
choiceValue: "oki",
choice: "Okinawa",
child: {
value: []
}
}, {
choiceValue: "tok",
choice: "Tokushima",
child: {
value: []
}
}]
}
}]
}
selectedCountry = {
result: "",
state: []
}
selectedState: any;
constructor() {
}
ngOnInit() {
}
changeCountryCallback() {
console.log("Country Value : ", this.selectedCountry['result']);
this.pickListValues['country'].forEach(element => {
console.log("Element : ", element);
if (element['choiceValue'] == this.selectedCountry['result']) {
this.selectedCountry['state'] = [];
this.selectedCountry['state'] = element['child']['value'];
}
})
}
changeStateCallback() {
console.log("State Value : ", this.selectedState);
}
}
My expected behavior is the radio group to be working fine with a single click after changing the country values frequently
Please watch up to end of the video you can understand my issue. Click here for video
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}" [selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="selectedState==state.choiceValue"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
You can accomplish by the above mentioned way([checked]="selectedState==state.choiceValue"). Here I checked which one is selected from the passed array. So on the first click, it should be working fine. Please try it and share the feedback.
<div>
<ion-label class="heading">Gender</ion-label>
<div *ngFor='let gend of gen'>\\ gen have my details
<ion-radio-group [(ngModel)]="register.Gender" [ngModelOptions]="{standalone: true}">
<ion-row style='margin-top:10px'>
<ion-col size='10'>
<ion-label style='color: #b4b4b4;margin:0 0 0 40px'> {{gend.name}}</ion-label>
</ion-col>
<ion-col size='2'>
<ion-radio [value]="gend.name"></ion-radio>\\value bind to ngModel
</ion-col>
</ion-row>
</ion-radio-group>
</div>
</div>

How to add text-area and select to the Alert in Ionic

I am working on Ionic App and I want to show I am showing the input fields in the alert but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my popupdetails.ts file:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-checkout',
templateUrl: 'checkout.html',
})
export class CheckoutPage {
constructor(public navCtrl: NavController, public navParams: NavParams,
public loadingCtrl: LoadingController, private alertCtrl: AlertController) {
}
presentPrompt() {
let alert = this.alertCtrl.create({
title: 'Submit Shipping Details',
inputs: [
{
name: 'name',
placeholder: 'Name'
},
{
name: 'mobilenumber',
placeholder: 'Mobile Number',
type: 'number'
},
{
name: 'pincode',
placeholder: 'Pincode',
type: 'number'
},
{
name: 'state',
placeholder: 'State',
},
{
name: 'city',
placeholder: 'City',
},
{
name: 'address',
placeholder: 'Address',
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Submit',
handler: data => {
console.log('Submit clicked');
}
}
]
});
alert.present();
}
}
In this, I have used the alert controller to the input fields but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my output currently coming.
I want this type of output with textarea and the select box.
Any help is much appreciated.
https://stackblitz.com/edit/ionic-x1os3c please check this link may hope it will help you
<ion-content padding style="background:white">
<ion-list no-lines>
<form>
<p style="font-weight:bold">Name</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='text'></ion-input>
</ion-item>
<p style="font-weight:bold">Mobile</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='tel'></ion-input>
</ion-item>
<p style="font-weight:bold">Country</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" readonly="true" type='text'></ion-input>
</ion-item>
</form>
<ion-grid>
<ion-row>
<ion-col>
<button color="secondary" ion-button float-right>Add</button>
<button color="light" ion-button float-right>Close</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
</ion-content>

How can I change an item in app.component.ts?

I am working on a project in Ionic, and when I login, I did set the storage('id') which was used in the app.component.ts to get the user details, but when I run the code, it didn't work, but when I reload the whole page (Ctrl + R), it then works.
Here is my code.
login.ts:
import {Component} from "#angular/core";
import {NavController, AlertController, ToastController, MenuController} from "ionic-angular";
import {HomePage} from "../home/home";
import {RegisterPage} from "../register/register";
import { ServicesProvider } from '../../providers/services/services';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
private user = {
email: '',
password: ''
}
private setputt:string;
constructor(public navCtrl: NavController,
public forgotCtrl: AlertController,
public menu: MenuController,
public toastCtrl: ToastController,
private storage: Storage,
public ServicesProvider: ServicesProvider
) {
this.menu.swipeEnable(false);
}
register() {
this.navCtrl.setRoot(RegisterPage);
}
login(user){
this.ServicesProvider.loginpost(user).subscribe(
data => {
if(data.success){
this.setputt = data.message;
if(this.setputt == 'Login Successfull'){
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
}
}
else{
this.setputt = data.message;
}
},
error => {
console.log(error);
}
)
}
// set a key/value
// storage.set('name', 'Max');
// // Or to get a key/value pair
// storage.get('age').then((val) => {
// console.log('Your age is', val);
// });
// storage.remove('name');
forgotPass() {
let forgot = this.forgotCtrl.create({
title: 'Forgot Password?',
message: "Enter you email address to send a reset link password.",
inputs: [
{
name: 'email',
placeholder: 'Email',
type: 'email'
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Send',
handler: data => {
console.log('Send clicked');
let toast = this.toastCtrl.create({
message: 'Email was sended successfully',
duration: 3000,
position: 'top',
cssClass: 'dark-trans',
closeButtonText: 'OK',
showCloseButton: true
});
toast.present();
}
}
]
});
forgot.present();
}
}
app.component.ts:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Storage } from '#ionic/storage';
import { ServicesProvider } from '../providers/services/services';
import { HomePage } from '../pages/home/home';
import {LoginPage} from "../pages/login/login";
import {ProfilePage} from "../pages/profile/profile";
import {FriendsPage} from "../pages/friends/friends";
import {YearbooksPage} from "../pages/yearbooks/yearbooks";
import {ChatPage} from "../pages/chat/chat";
import {FilesPage} from "../pages/files/files";
import {CheckLoginPage} from "../pages/check-login/check-login";
export interface MenuItem {
title: string;
component: any;
icon: string;
}
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = CheckLoginPage;
appMenuItems: Array<MenuItem>;
public FullNamer;
public pixr;
public id:number;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public storage: Storage,
public ServicesProvider: ServicesProvider
) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
});
this.storage.get('id').then((vals) => {
if (vals != null) {
this.ServicesProvider.getDetails(vals).subscribe(data=>{
// console.log(data);
this.pixr = this.ServicesProvider.theurl+data.pix;
this.FullNamer = data.fullname;
});
}
});
this.appMenuItems = [
{title: 'Home', component: HomePage, icon: 'home'},
{title: 'Files', component: FilesPage, icon: 'ios-folder'},
{title: 'Friends', component: FriendsPage, icon: 'ios-people'},
{title: 'Yearbooks', component: YearbooksPage, icon: 'ios-book'},
{title: 'Chat', component: ChatPage, icon: 'md-chatbubbles'}
];
}
ionViewCanEnter(){
}
openPage(page) {
this.nav.setRoot(page.component);
}
GoPages(){
this.nav.setRoot(ProfilePage);
}
logout() {
this.storage.remove('id');
this.storage.remove('FullName');
this.nav.setRoot(LoginPage);
}
}
app.html
<ion-menu side="left" id="authenticated" [content]="content">
<ion-header>
<ion-toolbar class="user-profile">
<ion-grid>
<ion-row>
<ion-col col-4>
<div class="user-avatar">
<img [src]="pixr">
</div>
</ion-col>
<ion-col padding-top col-8>
<h2 ion-text class="no-margin bold text-white">
{{FullNamer}}
</h2>
<span ion-text color="light">Customer</span>
</ion-col>
</ion-row>
<ion-row no-padding class="other-data">
<ion-col no-padding class="column">
<button ion-button icon-left small full class="round" color="light" menuClose (click)="GoPages()">
<ion-icon name="ios-person"></ion-icon>
Edit Profile
</button>
</ion-col>
<ion-col no-padding class="column">
<button ion-button icon-left class="round" small full color="light" menuClose (click)="logout()">
<ion-icon name="log-out"></ion-icon>
Log Out
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-toolbar>
</ion-header>
<ion-content color="primary">
<ion-list class="user-list">
<button ion-item menuClose class="text-1x" *ngFor="let menuItem of appMenuItems" (click)="openPage(menuItem)">
<ion-icon item-left [name]="menuItem.icon" color="primary"></ion-icon>
<span ion-text color="primary">{{menuItem.title}}</span>
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
service.ts:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
#Injectable()
export class ServicesProvider {
public theurl = 'http://localhost/HoleeSheet/php/';
public tittle = 'Holee Sheet';
public id:number;
constructor(public http: HttpClient, private storage: Storage) {
this.storage.get('id').then((valr) => {
if (valr != null) {
this.id = valr;
}
});
}
loginpost(user){
return this.http.put<obbbbs>(this.theurl+'login.php', {
email: user.email,
password: user.password
});
}
getDetails(humid){
console.log(humid);
return this.http.post<details>(this.theurl+'getDetails.php', {
id: humid
});
}
}
interface details{
'fullname': string,
'pix':string
}
interface obbbbs {
'success': 'boolean',
'message': 'string',
'id': 'string'
}
How can I solve this issue?
Welcome to Stack Overflow.
// LoginPage.login method (login.ts)
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
You're navigating to the home page before the value gets saved to storage. You should wait until the promise returned by this.storage.set is resolved before continuing navigation:
// LoginPage.login method (login.ts)
this.storage.set('id', data.id)
.then(() => this.navCtrl.setRoot(HomePage));

Ionic 3 Tab Navigation + side menu

The issue I am having is that when I use these both together, Tab navigation dissapears when using side menu navigation.
Using tab navigation makes the app work similar to a SPA i'm assuming, in that the page is loaded in the view. However, when I navigate using the side menu, I go directly to that page, which is circumventing the point of the tab navigation.
Is there a way to make these both work together?
app.component.ts:
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { Settings } from '../pages/settings/settings';
import { Journeys } from '../pages/journeys/journeys';
import { TabsPage } from '../pages/tabs/tabs';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = TabsPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public statusBar: StatusBar,
public splashScreen: SplashScreen) {
this.initializeApp();
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'Settings', component: Settings },
{ title: 'Journeys', component: Journeys }
];
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
this.nav.setRoot(page.component);
}
}
app.html:
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button menuClose ion-item *ngFor="let p of pages"
(click)="openPage(p)">
{{p.title}}
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
Tabs.ts:
import { Component } from '#angular/core';
import { HomePage } from '../home/home';
import { Journeys } from '../journeys/journeys';
import { Settings } from '../settings/settings';
#Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = HomePage;
tab2Root = Journeys;
tab3Root = Settings;
constructor() {
}
}
Tabs.html:
<ion-tabs>
<ion-tab [root]="tab1Root" tabTitle='Home' tabIcon='ios-home'></ion-tab>
<ion-tab [root]="tab2Root" tabTitle='Journeys' tabIcon='ios-car'></ion-tab>
<ion-tab [root]="tab3Root" tabTitle='Settings' tabIcon='md-settings'></ion-tab>
homepage.html:
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-grid>
<ion-row>
<ion-col col-12>
<p class='homepage_placeholder'>Homepage Placeholder</p>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Firstly, add tabIndex to your this.pages
this.pages = [
{ title: 'Home', component: HomePage, tabIndex:0 },
{ title: 'Settings', component: Settings, tabIndex:1 },
{ title: 'Journeys', component: Journeys, tabIndex:2 }
{ title: 'PageNotInTab', component: componentName }
];
And then, make your openPage() like this
openPage(page): void{
if(page.tabIndex){
this.nav.setRoot(TabsPage,{selectedIndex:page.tabIndex})
}else{
this.nav.setRoot(page.component,{})
}
}
Of cousre, TabsPage should be prepared before implementing the code above.
I leave out the details.
In TabsPage
ngAfterContentInit(){
if(this.navParams.data.hasOwnProperty("selectedIndex"))
this._selectedIndex = this.navParams.get("selectedIndex")
else
this._selectedIndex=0;
}

how do I create a modal view in ionic 2?

The documentation shows you how to open the modal, but isn't clear on what kind of page you're supposed to be passing to the open() method
example from docs:
import { Component } from '#angular/core';
import { ModalController, ViewController } from 'ionic-angular';
constructor(public modalCtrl: ModalController) {
}
presentContactModal() {
let contactModal = this.modalCtrl.create(ContactUs);
contactModal.present();
}
It isn't clear how where the 'ContactUs' object comes from, there is no import for it.
This example linked to here: https://ionicframework.com/docs/api/components/modal/ModalController/
import { Component } from '#angular/core';
import { ModalController, ViewController } from 'ionic-angular';
#Component(...)
class HomePage {
constructor(public modalCtrl: ModalController) { }
presentContactModal() {
let contactModal = this.modalCtrl.create(ContactUs);
contactModal.present();
}
}
///////////////below is the Contact us component which is define with in Homepage
#Component(...)
class ContactUs {
constructor(public viewCtrl: ViewController) {
}
dismiss() {
this.viewCtrl.dismiss();
}
}
The easiest way is to generate a modal content page:
ionic g ModalPage
Then you have to open modal-content.module.ts if the command creates this file, you have to change
imports: [
IonicModule.forChild(ModalPage),
],
TO :
imports: [
IonicModule.forRoot(ModalPage),
],
Then you have to add some html for the modal structure:
<ion-header>
<ion-toolbar>
<ion-title>
GO OUT
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss()">
<span ion-text color="primary" showWhen="ios">Cancel</span>
<ion-icon name="md-close" showWhen="android,windows"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<p> This is a modal test!!!! </p>
</ion-content>
Then you have to import in the declarations and entryComponents of the app module.
import { ModalPage } from '../pages/modal-page/modal-page';
#NgModule({
declarations: [
MyApp,
HomePage,
Main,
ModalPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
ModalPage
],
providers: [
StatusBar,
SplashScreen,
Device,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
Then in the page you want to execute the modal you have to add a function to the element you want to use to fire it.
<div full large class="button-el btn-goOut" (tap)="openModal()">
In the page you want to use the modal you have to import :
import { ModalPage } from '../modal-page/modal-page'
Important: this element should not be in the constructor, to call the modal you only have to do like this:
openModal(){
let modal = this.modalCtrl.create(ModalPage);
modal.present();
}
You can find a working example here in the docs repository.
It isn't clear how where the 'ContactUs' object comes from, there is
no import for it.
ContactUs is just another page, you can use any page from your app to create a modal with it.
import { Component } from '#angular/core';
import { ModalController, Platform, NavParams, ViewController } from 'ionic-angular';
#Component({
templateUrl: 'template.html'
})
export class BasicPage {
constructor(public modalCtrl: ModalController) { }
openModal(characterNum) {
let modal = this.modalCtrl.create(ModalContentPage, characterNum);
modal.present();
}
}
#Component({
template: `
<ion-header>
<ion-toolbar>
<ion-title>
Description
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss()">
<span ion-text color="primary" showWhen="ios">Cancel</span>
<ion-icon name="md-close" showWhen="android, windows"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item>
<ion-avatar item-left>
<img src="{{character.image}}">
</ion-avatar>
<h2>{{character.name}}</h2>
<p>{{character.quote}}</p>
</ion-item>
<ion-item *ngFor="let item of character['items']">
{{item.title}}
<ion-note item-right>
{{item.note}}
</ion-note>
</ion-item>
</ion-list>
</ion-content>
`
})
export class ModalContentPage {
character;
constructor(
public platform: Platform,
public params: NavParams,
public viewCtrl: ViewController
) {
var characters = [
{
name: 'Gollum',
quote: 'Sneaky little hobbitses!',
image: 'assets/img/avatar-gollum.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'River Folk' },
{ title: 'Alter Ego', note: 'Smeagol' }
]
},
{
name: 'Frodo',
quote: 'Go back, Sam! I\'m going to Mordor alone!',
image: 'assets/img/avatar-frodo.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'Shire Folk' },
{ title: 'Weapon', note: 'Sting' }
]
},
{
name: 'Samwise Gamgee',
quote: 'What we need is a few good taters.',
image: 'assets/img/avatar-samwise.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'Shire Folk' },
{ title: 'Nickname', note: 'Sam' }
]
}
];
this.character = characters[this.params.get('charNum')];
}
dismiss() {
this.viewCtrl.dismiss();
}
}
In the example below, ModalContentPage is used to create the modal. Please notice that it's recommended to include just one component per file, so ideally you'd create the page to use as a modal in a different file.