2016-07-15 58 views
2

我是Angular2和Ionic2中的一个初学者。我正在尝试使用Ionic2的Tabs组件构建自己的小应用程序。Ionic2更改从子页面tabs selectedIndex属性

我希望能够使用我的childpage中的按钮来更改选项卡。我尝试过使用NavController.setRoot()NavController.push(),但没有一个具有所需的行为。

setRoot(Homepage)设置正确的视图,但不会更改选项卡菜单中的选定选项卡。 push(Homepage)设置正确的视图,但Tabs菜单不再可见。

我有点困惑,我应该如何与TabsPage(拥有标签的@Component)通过我的单页进行通信。

谢谢!

+0

我把它从组件有同样的问题。弹出(),推()与标签只是不按预期工作。 – Mukus

回答

2

嘛,应该有这样做的更简单的方法,但我没有这样说:

因为为了改变激活的标签,你应该从标签组件做到这一点,我用了一个共享服务来处理标签页内部的页面之间的通信。标签容器(包含标签的组件)。即使您可能可以使用Events来执行此操作,但我喜欢共享服务方法,因为它更容易理解,并且在应用程序开始增长时也很重要。

所以基本上TabServices只创建一个Observable允许标签容器订阅它,并且还声明了changeTabInContainerPage()方法将从标签页被调用。

import {Injectable} from '@angular/core'; 
import {Platform} from 'ionic-angular/index'; 
import {Observable} from '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); 
    } 

} 

然后,在每个页面(选项卡内)我们只添加一个按钮,并绑定,要调用服务的方法:

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 } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { TabService } from 'tabService.ts'; 

@Component({ 
    templateUrl:"page1.html" 
}) 
export class Page1 { 

    constructor(private tabService: TabService) { } 

    public changeTab() { 
    this.tabService.changeTabInContainerPage(1); 
    } 
} 

最后,在tabs组件中,我们只订阅服务中的方法,然后我们ch安格与this.tabRef.select(index);

import { Component, ViewChild } from "@angular/core"; 
import { Page1 } from './page1.ts'; 
import { Page2 } from './page2.ts'; 
import { TabService } from 'tabService.ts'; 


@Component({ 
    templateUrl: 'tabs.html' 
}) 
export class TabsPage { 
    @ViewChild('myTabs') tabRef: Tabs; 

    tab1Root: any = Page1; 
    tab2Root: any = Page2; 

    constructor(private tabService: TabService){ 
    this.tabService.tabChange.subscribe((index) => { 
     this.tabRef.select(index); 
    }); 
    } 
} 

选定的选项卡请注意,我们通过在ion-tabs要素加上#myTabs获取到Tabs实例的引用,我们与@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> 
+0

谢谢,这工作,我有点困惑应该怎么做,事件。我尝试过使用[这个例子](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent),但这里的TabsPage模板不包含tab指令。 –

+1

这适用于Ionic 2发布版本。 – Mukus