从主页导航时,导航到页面并突出显示菜单项

时间:2017-07-20 13:29:08

标签: javascript angular typescript ionic2 angular2-template

我目前正在创建一个带有Ionic 2+和Angular 2的应用程序。它目前工作得很好但我在导航和突出显示菜单项时遇到了一些麻烦。 我的应用程序主页上有一个联系人按钮(home.html和home.ts)

Contact button on homepage

我可以使用以下方式导航到正确的页面:

this.navCtrl.root(ContactPage)

但是菜单中的页面不是(当我从侧边菜单导航时):

Side menu highlighted

我的app.component.ts中有一个activePage参数,当我点击侧面菜单项时,会设置活动页面。在加载菜单时通过加载样式时检查此参数是否为真:

isActive(page: PageInterface){
    if(this.activePage == page)
    {
      return true
    }
}

当我点击主页上的按钮时,我不知道如何在home.ts的app.component.ts中设置此参数。

有没有人有提示或技巧让我朝着正确的方向前进。

更多代码:

我如何生成菜单项的示例:

<ion-item [class.activeItem]="isActive(p)" no-lines *ngFor="let p of MiscPages" (click)="openPage(p)">

app.component.ts页面列表的结构:

this.MiscPages = [
  { title: 'MENU.INFO_BTN', name: 'Information', component: InformationPage, icon: 'ios-information-circle' },
  { title: 'MENU.CONTACT_BTN', name: 'Contact', component: ContactPage, icon: 'ios-paper-plane' },
  { title: 'MENU.SETTINGS_BTN', name: 'Settings', component: SettingsPage, icon: 'ios-settings' }
]

1 个答案:

答案 0 :(得分:2)

创建如下共享服务:

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService {

  private currentPage: string;
  constructor() { }

  getData() {
    return this.currentPage;
  }

  setData(page) {
    this.currentPage = page;
  }
}

在您的应用模块中导入服务,如下所示:

import { SharedService } from './shared/shared.service'; //Change the path as per your file location

将服务添加到providers数组中,如下所示:

@NgModule({
      declarations: [],
      imports: [],
      providers: [SharedService],
      bootstrap: [AppComponent]
    })

在组件中注入此服务,并使用get()和set()方法保存和检索当前活动的页面:

this.SharedService.setData('Current Active Page'); // To save current page
this.SharedService.getData('Current Active Page'); // To get current page

您可以根据从getData()方法获得的响应来更改css。我希望这是有道理的。