Reputation: 6744
I have a tab based ionic 2 typescript app.
I want to change the default tab shown when the app is launched depending on whether or not the user is logged in.
The code I am trying to use is giving me an error of _this.tabRef is undefined
My app.ts file looks like this:
import {Component, ViewChild} from '@angular/core';
import {Platform, ionicBootstrap, NavController, Tabs} from 'ionic-angular';
import {Http, Headers, RequestOptions, HTTP_PROVIDERS, XSRFStrategy, CookieXSRFStrategy} from '@angular/http';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
import {LoginPage} from './pages/login/login';
import {TabsPage} from './pages/tabs/tabs';
import {DjangoAuth} from './providers/djangoAuth';
import {API_ENDPOINT} from '../app_settings';
import {AUTH_ENDPOINT} from '../app_settings';
@Component({
template: '<ion-nav [root]="rootPage"></ion-nav>'
})
export class MyApp {
rootPage: any = HomePage;
@ViewChild('twipTabs') tabRef: Tabs;
constructor(public platform: Platform, public djangoAuth: DjangoAuth) {
this.rootPage = TabsPage;
platform.ready().then(() => {
StatusBar.styleDefault();
djangoAuth.initialize(AUTH_ENDPOINT, false);
// Check if user is logged in
djangoAuth.authenticationStatus()
.then((data:any) => {
alert('You are logged in');
// Select the photo upload tab
this.tabRef.select(2);
},
(err:any)=>{
alert('You are not logged in');
// Select the login tab
this.tabRef.select(1);
});
});
}
}
ionicBootstrap(MyApp, [HTTP_PROVIDERS,
DjangoAuth,
Tabs,
{provide:XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')}]);
My tabs.html looks like this:
<ion-tabs #twipTabs>
<ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="Login" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Submit" tabIcon="contacts"></ion-tab>
</ion-tabs>
And my tabs.ts looks like this:
import {Component, ViewChild, Injectable} from '@angular/core';
import {Tabs} from 'ionic-angular';
import {HomePage} from '../home/home';
import {PhotoPage} from '../photo/photo';
import {LoginPage} from '../login/login';
import {ResetPasswordPage} from '../reset-password/reset-password';
@Component({
templateUrl: 'build/pages/tabs/tabs.html'
})
@Injectable()
export class TabsPage {
@ViewChild('twipTabs') tabRef: Tabs;
private tab1Root: any;
private tab2Root: any;
private tab3Root: any;
constructor() {
this.tab1Root = HomePage;
this.tab2Root = LoginPage;
this.tab3Root = PhotoPage;
}
}
Upvotes: 0
Views: 1042
Reputation: 5706
You can selectedIndex instead of the view child on the tabs. This will save you the trouble of getting the reference
<ion-tabs [selectedIndex]="selected">
this.selected = 1;
More info on their component page http://ionicframework.com/docs/v2/api/components/tabs/Tabs/
Upvotes: 1