Ionic - Активное состояние меню не меняется при нажатии - PullRequest
0 голосов
/ 06 июля 2018

enter image description here

Я использую приложение Ionic Side-Menu. Изображение выше подчеркивает мою проблему. Я хотел бы, чтобы активное состояние меню было изменено при переходе на эту конкретную страницу. Состояние меню прекрасно работает при нажатии на элемент меню для навигации и нигде в другом месте для навигации.

При нажатии «Перейти к списку» из дома, я использую следующий код в моей домашней странице.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ListPage } from '../list/list';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  listPage =  ListPage; 
  constructor(public navCtrl: NavController) {

  }

  goToList(){
    this.navCtrl.setRoot(this.listPage);
  }
}

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { GalleryPage } from '../pages/gallery/gallery';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = HomePage;
  activePage: any;

  pages: Array<{title: string, component: any}>;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'Home', component: HomePage },
      { title: 'List', component: ListPage },
      { title: 'Gallery', component: GalleryPage}
    ];

    this.activePage = this.pages[0];

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
    this.activePage = page;
  }

  checkActive(page){
    return page === this.activePage;
  }
}

Любая помощь в этом?

1 Ответ

0 голосов
/ 07 июля 2018

Я смог сам найти ответ и, следовательно, опубликовать его для дальнейшего использования кем-то еще.

Добавлен код внутри ngAfterViewInit () , и он, похоже, работает.

ngAfterViewInit () вызывается каждый раз, когда изменяется состояние страницы, а view.instance.constructor.name дает вам имя конструктора текущей страницы, и вы можете просто сравнить его с вашим Массив меню, чтобы узнать, к какой странице вы перешли, и просто установить ее как активную.

См. Полный код ниже

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { GalleryPage } from '../pages/gallery/gallery';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = HomePage;
  activePage: any;

  pages: Array<{title: string, component: any, active: boolean}>;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'Home', component: HomePage, active: false },
      { title: 'List', component: ListPage, active: false },
      { title: 'Gallery', component: GalleryPage, active: false}
    ];

    this.activePage = this.pages[0];

  }

  ngAfterViewInit(){
    this.nav.viewDidEnter.subscribe((view) => {
      for(let i = 0 ; i < this.pages.length ; i++){
        if(this.pages[i].component.name == view.instance.constructor.name){
           this.activePage = this.pages[i];
           break;
        }
      }
    });
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
    this.activePage = page;
  }

  checkActive(page){
    // console.log(page.title, this.activePage.title, page === this.activePage);
    return page === this.activePage;
  }
}
...