Ionic2 从子页面更改 Tabs selectedIndex 属性

Ionic2 change Tabs selectedIndex property from a childpage

我是 Angular2 和 Ionic2 的初学者。我正在尝试使用 Ionic2 的 Tabs 组件构建我自己的小应用程序。

我希望能够使用子页面中的按钮更改选项卡。我尝试使用 NavController.setRoot()NavController.push(),但其中 none 具有所需的行为。

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

我对如何从我的单个页面与 TabsPage(包含选项卡的 @Component)进行通信感到有点困惑。

谢谢!

嗯,应该有更简单的方法来做到这一点,但我是这样做的:

因为要更改活动选项卡,您应该从选项卡组件中进行,我使用了 共享服务 来处理 内部页面之间的通信选项卡选项卡容器(包含选项卡的组件)。尽管您可能可以使用 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组件中,我们只订阅服务中的方法,然后我们用this.tabRef.select(index);

改变选中的tab
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 实例的引用,并且我们使用 [=22= 从组件中获取它]

<ion-tabs #myTabs>
  <ion-tab [root]="tab1Root" tabTitle="Tab 1"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Tab 2"></ion-tab>
</ion-tabs>