【问题标题】:Ionic 2: How to use ViewChild instead of app.getComponentIonic 2:如何使用 ViewChild 而不是 app.getComponent
【发布时间】:2017-10-06 22:40:48
【问题描述】:

我正在将我的 ionic 2 应用程序迁移到删除 app.getComponent 的 RC 版本。 在他们的 github 发布说明中,他们谈到了使用 ViewChild,我该如何正确使用它?

之前(在 RC 版本之前工作):

openPage(page) {
  this.app.getComponent('leftMenu').close();   
  // navigate to the new page if it is not the current page
  let nav = this.app.getComponent('nav');
  nav.setRoot(page.component);  
}

之后:

@Component({
  templateUrl: 'build/app.html',
  queries: {
   leftMenu: new ViewChild('leftMenu'),
   nav: new ViewChild('content')
  }
})

....

openPage(page) {
    // close the menu when clicking a link from the menu
    this.leftmenu.close();
    // navigate to the new page if it is not the current page
    this.nav.setRoot(page.component);
 }

我正在尝试获取“leftMenu”组件,但没有成功。我得到的错误是

browser_adapter.js:77 原始异常:TypeError:无法读取 未定义的属性“关闭”

【问题讨论】:

标签: angular typescript ionic-framework ionic2 ionic3


【解决方案1】:

按照Conference App 中的做法(并稍作改动以简化代码):

import {Component, ViewChild} from '@angular/core';
import {ionicBootstrap, ..., Platform, MenuController} from 'ionic-angular';
...

@Component({
  templateUrl: 'build/app.html',
  queries: {
    nav: new ViewChild('content')
  }
})
class ConferenceApp {
  static get parameters() {
    return [[...], [Platform], [MenuController]]
  }

  constructor(..., platform, menu) {
    this.menu = menu;

    // Call any initial plugins when ready
    platform.ready().then(() => {
       ...
    });

 openPage(page) {
     this.menu.close();
     this.nav.setRoot(page);    
  }
}

ionicBootstrap(ConferenceApp, [...], {
  // config
});

据我所知,您可以使用MenuController的实例来执行close()方法并隐藏侧边菜单。

如果您需要此代码的 TypeScript 版本,只需添加评论,我会更新答案,不想添加它以保持答案简短。

【讨论】:

  • 嗨,如果说我希望获得 'leftMenu' 的元素,我该怎么做?
猜你喜欢
  • 2017-04-12
  • 2016-10-01
  • 2018-07-11
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多