ionic 2/3: How to select tabs dynamically - ionic-framework

I created a sidemenu app in Ionic 2 which contains a Main Tab and 3 sub tab pages.
It looks like this:
This is the code for Main tabs page:
<ion-header>
<ion-navbar #content color="black">
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title >Main Tab</ion-title>
</ion-navbar>
</ion-header>
<ion-tabs [selectedIndex]="mySelectedIndex" #myTabs>
<ion-tab [root]="tabARoot" tabTitle="Tab A" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tabBRoot" tabTitle="Tab B" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tabCRoot" tabTitle="Tab C" tabIcon="information-circle"></ion-tab>
</ion-tabs>
It contains 3 sub tab pages with some gibberish on it.
This is how my side menu looks like.
So when a user clicks on Tab B link from side menu, he should navigate to main tabs page with Tab B as selected. But now when I click, Tab A is selected by default.
Is it possible to change this behavior?
My app.component.ts file looks like this
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, App, Tabs } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { MainPage } from '../pages/main/main';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = MainPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private app: App) {
this.initializeApp();
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Tab A', component: MainPage },
{ title: 'Tab B', component: MainPage },
{ title: 'Tab C', component: MainPage },
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
}
From somewhere I got a solution which didn't work, obviously.
in that solution, it was mentioned to do it like given below but it didn't work'
this.nav.setRoot(page.component, {tabIndex: 2});

There is a property called selectedIndex in ion-tabs component to set the default tab. Since you are passing tabIndex while clicking the main tab you can do something like this
In the controller
selectedTabIndex = navParams.get('tabIndex');
In the view
<ion-tabs [selectedIndex]="selectedTabIndex">
<ion-tab [root]="tabA"></ion-tab>
<ion-tab [root]="tabB"></ion-tab>
<ion-tab [root]="tabC"></ion-tab>
</ion-tabs>
Else if you want to select any tabs programatically from controller you can do this, first get the reference of your tabs and then you can use the select() function to set the selected tab you want by passing the index
#ViewChild('myTabs') tabRef: Tabs;
ionViewDidLoad() {
this.tabRef.select(1, { animate: false });
}

#john Doe
set root page = 'MenuPage' page
rootPage = 'MenuPage'
try below code:
`
src/pages/menu/menu.html :
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item menuClose *ngFor="let p of pages" (click)="openPage(p)">
<ion-icon item-start [name]="p.icon" [color]="isActive(p)"></ion-icon>
{{ p.title }}
</button>
</ion-list>
</ion-content>
</ion-menu>
<!-- main navigation -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
src/pages/menu/menu.ts:
import { Tab2Page } from './../tab2/tab2';
import { Tab1Page } from './../tab1/tab1';
import { TabsPage } from './../tabs/tabs';
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, Nav } from 'ionic-angular';
export interface PageInterface {
title: string;
pageName: string;
tabComponent?: any;
index?: number;
icon: string;
}
#IonicPage()
#Component({
selector: 'page-menu',
templateUrl: 'menu.html',
})
export class MenuPage {
// Basic root for our content view
rootPage = 'TabsPage';
// Reference to the app's root nav
#ViewChild(Nav) nav: Nav;
pages: PageInterface[] = [
{ title: 'Tab 1', pageName: 'TabsPage', tabComponent: 'Tab1Page', index: 0, icon: 'home' },
{ title: 'Tab 2', pageName: 'TabsPage', tabComponent: 'Tab2Page', index: 1, icon: 'contacts' },
{ title: 'Special', pageName: 'SpecialPage', icon: 'shuffle' },
];
constructor(public navCtrl: NavController) { }
openPage(page: PageInterface) {
let params = {};
// The index is equal to the order of our tabs inside tabs.ts
if (page.index) {
params = { tabIndex: page.index };
}
// The active child nav is our Tabs Navigation
if (this.nav.getActiveChildNav() && page.index != undefined) {
this.nav.getActiveChildNav().select(page.index);
} else {
// Tabs are not active, so reset the root page
// In this case: moving to or from SpecialPage
this.nav.setRoot(page.pageName, params);
}
}
isActive(page: PageInterface) {
// Again the Tabs Navigation
let childNav = this.nav.getActiveChildNav();
if (childNav) {
if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {
return 'primary';
}
return;
}
// Fallback needed when there is no active childnav (tabs not active)
if (this.nav.getActive() && this.nav.getActive().name === page.pageName) {
return 'primary';
}
return;
}
}
src/pages/tabs/tabs.html
<ion-tabs [selectedIndex]="myIndex">
<ion-tab [root]="tab1Root" tabTitle="Tab 1" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="Tab 2" tabIcon="contacts"></ion-tab>
</ion-tabs>
src/pages/tabs/tabs.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-tabs',
templateUrl: 'tabs.html',
})
export class TabsPage {
tab1Root: any = 'Tab1Page';
tab2Root: any = 'Tab2Page';
myIndex: number;
constructor(navParams: NavParams) {
// Set the active tab based on the passed index from menu.ts
this.myIndex = navParams.data.tabIndex || 0;
}
}
thanks

Related

Ionic4 - ion-select does not correctly update after dynamically added option

The issue is that ion-select multi selection drop-down does not update (selection and as a consequence its control name) after dynamically updating underlying values list.
I have tried triggering change detection manually to pickup the changes but doesn't have an effect.
The following is the minimalistic snippet that illustrates the issue:
#Component({
selector: 'app-root',
template: `
<ion-button color="primary" (click)="AddItem()">Add Item</ion-button>
<ion-item>
<ion-label>Broken dropdown</ion-label>
<ion-select
multiple="true"
placeholder="Broken dropdown"
[compareWith]="compareWith"
>
<ion-select-option *ngFor="let item of stuff" [value]="item" [selected]="item.selected">
{{item.name}}
</ion-select-option>
</ion-select>
</ion-item>
`
})
export class AppComponent {
public stuff = [{ name: 'item1', selected: false }, { name: 'item2', selected: true }];
constructor(private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
AddItem() {
this.stuff.push({ name: 'item3', selected: true });
}
compareWith(e1, e2) {
return e1 && e2 ? e1.name === e2.name : e1 === e2;
}
}
After clicking "Add Item" button I would expect the control name to be updated as well as after opening the drop-down the item2 and item3 would be selected.
I did workaround the issue by manually manipulating control but I would like to understand where the issue is that it doesn't update itself out of the box.
Thanks!

Ionic 3 Google Map does not display on Android + IOS

I use Ionic 3 version and I try to add a page into my app, to display a map with markers.
I already use for my app a Google Map Id for Autocomplete (Google places...).
I went to Google APIs and I added Map Embed, Javascript etc... to my API Key.
But The page appears with "Google" in the bottom and the display button", but the map is empty.
See attached file...
Install the Cordova and Ionic Native plugins:
$ ionic cordova plugin add https://github.com/mapsplugin/cordova-plugin-googlemaps#multiple_maps --variable API_KEY_FOR_ANDROID="AIzaSyB6mEnxH4vC+++++++++9wnXXNNmK2co" --variable API_KEY_FOR_IOS="AIzaSyB6mEnxH4v++++++++++++++wnXXNNmK2co"
$ npm install --save #ionic-native/google-maps
Home.ts:
import { NavController } from 'ionic-angular';
import { Component, ViewChild, ElementRef } from '#angular/core';
import { GoogleMaps, CameraPosition, GoogleMapsEvent, GoogleMap, MarkerOptions, Marker } from "#ionic-native/google-maps";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, private googleMaps: GoogleMaps) {
}
ngAfterViewInit() {
this.loadMap();
}
loadMap() {
// make sure to create following structure in your view.html file
// and add a height (for example 100%) to it, else the map won't be visible
// <ion-content>
// <div #map id="map" style="height:100%;"></div>
// </ion-content>
// create a new map by passing HTMLElement
let element: HTMLElement = document.getElementById('map');
let map: GoogleMap = this.googleMaps.create(element);
// listen to MAP_READY event
// You must wait for this event to fire before adding something to the map or modifying it in anyway
map.one(GoogleMapsEvent.MAP_READY).then(
() => {
console.log('Map is ready!');
// Now you can add elements to the map like the marker
}
);
// create CameraPosition
let position: CameraPosition = {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
};
// move the map's camera to position
}
}
Home.HTML
Home.html :
<ion-header>
<ion-navbar>
<ion-title>
Map
</ion-title>
<ion-buttons end>
<button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map" style="height:100%;"></div>
</ion-content>
Home.scss
page-home {
}
Do not use the ngAfterViewInit.
You must wait platform.ready()
// Wait the native plugin is ready.
platform.ready().then(() => {
this.loadMap();
});
Full code is https://github.com/mapsplugin/cordova-plugin-googlemaps-doc/blob/master/v2.0.0/ionic-native/README.md
Repo: https://github.com/mapsplugin/ionic-google-maps
The current official document page is wrong. I sent a pull request, but it's waiting now.
https://github.com/ionic-team/ionic-native/pull/1834
Please try below code and make sure you are using correct API key, write following code in your .ts file:
ionViewDidLoad() {
this.loadMap();
}
loadMap() {
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
}
};
this.map = this.googleMaps.create('map_canvas', mapOptions);
// Wait the MAP_READY before using any methods.
this.map.one(GoogleMapsEvent.MAP_READY)
.then(() => {
console.log('Map is ready!');
this.map.addMarker({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: {
lat: 43.0741904,
lng: -89.3809802
}
})
.then(marker => {
marker.on(GoogleMapsEvent.MARKER_CLICK)
.subscribe(() => {
alert('clicked');
});
});
});
}
In your .html file define map like below
<ion-content>
<div id="map_canvas" style="height: 100%;"></div>
</ion-content>

image selection des not work in ionic 2 app

i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
image640:any;
constructor(public navCtrl: NavController,public camera : Camera)
{
}
openGallery()
{
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
this.camera.getPicture(
options
).then(
(imageData)=>
{
this.image640 = 'data:image/jpeg;base64,'+imageData;
},
(err) =>
{
console.log(err);
}
);
}
}
And the code of the home.html is below :
<ion-header>
<ion-navbar>
<ion-title align="center">
Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<img src="image640" *ngIf="image640"/>
<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>
</ion-content>
but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?
Set options
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
Then select photos like this
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('android') && sourceType ===
this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library
//your code goes here
} else { //when capturing by camera
//your code goes here
}

getting Nav as undefined in root page

I recently upgraded from Ionic 2 to Ionic 3. As soon as I upgraded, I am getting Nav as undefined in root page.
//app.component.ts
import { Component, ViewChild, Renderer } from '#angular/core';
import { Platform, Nav, MenuController } from 'ionic-angular';
#Component({
templateUrl: `app.html`
})
export class MyApp {
#ViewChild(Nav) nav : NavController ;
rootPage: any;
authHandler : any;
pages: Array<{title: string, component: any, icon: string}>;
urls: Array<{title: string, url: string, icon: string}>;
contact: Array<{title: string, url: string, icon: string}>;
constructor(public platform: Platform,
public renderer : Renderer,
public menu: MenuController,
public loginService : LoginService,
public util : UtilityService,
public statusBar: StatusBar,
public keyboard: Keyboard) {
this.initializeApp();
console.log("THis is nav object :: ", this.nav);
}
//app.html
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
output in the console:
THis is nav object :: undefined
Is something changed in Ionic 3 what I have to do In order to make that work?
you have to use ion-nav template
#Component({
template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
like describe here : https://ionicframework.com/docs/api/navigation/NavController/#navigating-from-the-root-component
Or you can add ion-nav tag in your app.html :
<ion-nav id="nav" [root]="rootPage" #content swipe-back-enabled="false"></ion-nav>

ionic 2 Alert not working on webpage

I would like to raise an alert on Ionic2 when the device does not have a Camera.
When i launch : ionic serve
then i try to display the message as follow :
let alert = Alert.create({
title: 'Camera not found',
subTitle: 'It seems your camera is not working on your device',
buttons: ['Ok']
});
this.nav.present(alert);
i have a javascript error
Uncaught EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: rootNav.getActive is not a function
ORIGINAL STACKTRACE:
TypeError: rootNav.getActive is not a function
at Tab.NavController.present (http://localhost:8100/build/js/app.bundle.js:46996:36)
at SmartScan.takePicture (http://localhost:8100/build/js/app.bundle.js:60864:23)
at AbstractChangeDetector.ChangeDetector_SmartScan_0.handleEventInternal (eval at <anonymous> (http://localhost:8100/build/js/app.bundle.js:14578:17), <anonymous>:185:36)
at AbstractChangeDetector.handleEvent (http://localhost:8100/build/js/app.bundle.js:13892:25)
at AppView.dispatchEvent (http://localhost:8100/build/js/app.bundle.js:18772:46)
at AppView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:18766:22)
at DefaultRenderView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:33592:39)
at eventDispatcher (http://localhost:8100/build/js/app.bundle.js:33258:22)
at http://localhost:8100/build/js/app.bundle.js:33329:40
In alert.js:
import {Page, Alert, NavController} from 'ionic-angular';
#Page({
templateUrl: 'build/pages/alert/alert.html'
})
export class AlertPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['Ok']
});
this.nav.present(alert);
}
}
In alert.html:
<button block dark (click)="showAlert()">test</button>
Try this:
with this structure of folder and files
In:
home.html
<ion-header>
<ion-navbar>
<ion-title>Ionic 2 Notifications</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button block dark (click)="showAlert()">Alert</button>
</ion-content>
In:
home.ts
import {Component} from "#angular/core";
import {NavController, AlertController} from 'ionic-angular';
#Component({
templateUrl: 'home.html'
})
export class HomePage {
constructor(public alertCtrl: AlertController) {
}
showAlert() {
let alert = this.alertCtrl.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['OK']
});
alert.present();
}
}
I got this information from the documentation site:
https://ionicframework.com/docs/v2/components/#action-sheets
I am also working on ionic2 and was in the need to implement "PopUp" window in my existing application.
I try many for that by does not get my task accomplished, finally i did something like this-
pop-up.html
<button block dark (click)="showAlert()">Help Window</button>
pop-up.ts
import { Component } from '#angular/core';
import { Alert, NavController, NavParams} from 'ionic-angular';
#Component({
templateUrl: 'build/pages/pop-up/pop-up.html',
})
export class PopUpPage {
static get parameters() {
return [[NavController]];
}
constructor(private nav: NavController) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'Help Window!',
subTitle: 'Mindfulness is here for you and your soul. We are intended to stablish your connection to All Mighty.',
buttons: ['Cancle']
});
this.nav.present(alert);
}
}
And that work fine for me.
Hope it will work for you too.
It seems that is not yet ready ...
investigating the code
this.nav.present(alert);
it is passing here and returns :
if (rootNav['_tabs']) {
// TODO: must have until this goes in
// https://github.com/angular/angular/issues/5481
void 0;
return;
}