angular - Ionic2 change Tabs selectedIndex property from a childpage -
i'm kind of beginer in angular2 , ionic2. trying build own small app using ionic2's tabs component.
i want able change tab using button in childpage. have tried using navcontroller.setroot()
, navcontroller.push()
none of them have desired behaviour.
setroot(homepage)
sets correct view doesn't change selected tab in tab menu. push(homepage)
sets correct view tabs menu not visible anymore.
i bit confused how should comnunicate tabspage (the @component holds tabs) single pages.
thanks!
well, there should easier way this, did way:
because in order change active tab should tabs component, used shared service handle communication between the pages inside tab , the tab container (the component holds tabs). though events shared service approach because easier understand , mantain when applications start growing.
so tabservices
only creates observable
allow tabs container subscribe it, , declares changetabincontainerpage()
method called tab pages.
import {injectable} '@angular/core'; import {platform} 'ionic-angular/index'; import {observable} 'rxjs/observable'; @injectable() export class tabservice { private tabchangeobserver: any; public tabchange: any; constructor(private platform: platform){ this.tabchangeobserver = null; this.tabchange = observable.create(observer => { this.tabchangeobserver = observer; }); } public changetabincontainerpage(index: number) { this.tabchangeobserver.next(index); } }
then, in each page (inside tabs) add button , bind method calls service:
page1.html
<ion-content class="has-header"> <div padding style="text-align: center;"> <h1>page 1</h1> <button secondary (click)="changetab()">select next tab</button> </div> </ion-content>
page1.ts
import { component } '@angular/core'; import { observable } 'rxjs/observable'; import { tabservice } 'tabservice.ts'; @component({ templateurl:"page1.html" }) export class page1 { constructor(private tabservice: tabservice) { } public changetab() { this.tabservice.changetabincontainerpage(1); } }
and finally, in tabs component, subscribe method in service, , change selected tab this.tabref.select(index);
import { component, viewchild } "@angular/core"; import { page1 } './page1.ts'; import { page2 } './page2.ts'; import { tabservice } 'tabservice.ts'; @component({ templateurl: 'tabs.html' }) export class tabspage { @viewchild('mytabs') tabref: tabs; tab1root: = page1; tab2root: = page2; constructor(private tabservice: tabservice){ this.tabservice.tabchange.subscribe((index) => { this.tabref.select(index); }); } }
please notice we're getting reference tabs
instance adding #mytabs
in ion-tabs
element, , component @viewchild('mytabs') tabref: tabs;
<ion-tabs #mytabs> <ion-tab [root]="tab1root" tabtitle="tab 1"></ion-tab> <ion-tab [root]="tab2root" tabtitle="tab 2"></ion-tab> </ion-tabs>
Comments
Post a Comment