Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2: How to use ViewChild instead of app.getComponent

I'm migrating my ionic 2 app into RC version in which app.getComponent is removed. In their github release notes, they said about using ViewChild, how do I properly use it?

Before(working before RC version):

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);  
}

After:

@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);
 }

I'm trying to get the 'leftMenu' component without any success. The error i get is

browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: Cannot read property 'close' of undefined

like image 252
Gene Avatar asked Nov 28 '25 13:11

Gene


1 Answers

Following how it's done in the Conference App (and changing it just a little bit to simplify the code):

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
});

So as far as I know, you can use the instance of the MenuController to execute the close() method and hide the side menu.

If you need the TypeScript version of this code, just add a comment and I'll update the answer, didn't want to add it to keep the answer short.

like image 89
sebaferreras Avatar answered Nov 30 '25 04:11

sebaferreras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!