【问题标题】:Navigate to page and highlight menu item when navigating from home page从主页导航时导航到页面并突出显示菜单项
【发布时间】:2017-07-20 13:29:08
【问题描述】:

我目前正在使用 Ionic 2+ 和 Angular 2 创建一个应用程序。它目前运行良好,但我在导航和突出显示菜单项时遇到了一些问题。 我的应用主页上有一个联系按钮(home.html 和 home.ts)

我可以使用以下命令导航到正确的页面:

this.navCtrl.root(ContactPage)

但是页面没有像这样在菜单中突出显示(当我从侧面菜单导航时):

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

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

当我点击主页上的按钮时,我不知道如何在 app.component.ts 中从 home.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' }
]

【问题讨论】:

  • 使用共享服务来跟踪当前处于活动状态的页面。
  • 因此,我没有在 app.component 中使用局部变量,而是创建了一个包含此变量但可用于完整应用程序(我在哪里导入)的服务?
  • 是的,没错。使用 get() 和 set() 方法创建服务。让我将其发布为答案。
  • 我尝试这样做,但侧边菜单没有更新。我会等你的答复。
  • 回答有意义吗?

标签: javascript angular typescript ionic2 angular2-template


【解决方案1】:

像这样创建一个共享服务:

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

像这样将服务添加到提供者数组中:

@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。我希望这是有道理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多