ionic 2 sidemenu - 组件内的 navCtrl

ionic 2 sidemenu - navCtrl inside a component

我正在使用带侧边菜单的 ionic 2 入门模板。

原来的app.html是这样的

<ion-menu [content]="content">
    <ion-toolbar>
        <ion-title>Menu</ion-title>
    </ion-toolbar>

    <ion-content>
        <ion-list>
            <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
                {{p.title}}
            </button>
        </ion-list>
    </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

我想用这样的组件替换菜单内容

<ion-menu [content]="content">
    <st-menu></st-menu>
</ion-menu>

我的menu.component.ts是这样的,基本是从原来的app.ts文件中复制过来的

import {Page1} from "../pages/page1/page1";
import {Page2} from "../pages/page2/page2";
import {Nav, NavController} from "ionic-angular";

@Component({
    selector: 'st-menu',
    templateUrl: 'build/menu/menu.html'
})

export class MenuCmp {
    @ViewChild(Nav) nav: Nav;

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

    constructor(private navCtrl:NavController) {
        this.pages = [
            { title: 'Home', component: HomePage },
            { title: 'Page uno', component: Page1 },
            { title: 'Page dos', component: Page2 }
        ];
    }
    openPage(page) {
        this.nav.setRoot(page.component);
    }

}

和menu.html这样

<ion-toolbar>
    <ion-title>Menu</ion-title>
</ion-toolbar>

<ion-list>
    <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
        {{p.title}}
    </button>
</ion-list>

现在,当我在菜单中单击时出现错误:

无法读取未定义的 属性'setRoot'

我已经通过替换进行了测试 this.nav.setRoot(page.component) 与 this.nav.setRoot(主页); 它仍然是一样的。 当我用 navCtrl 替换 nav(提供并注入)时,它说 this.navCtrl.setRoot 不是函数

有什么建议吗?谢谢!

你应该尝试将父组件的navCtrl传递给openPage函数, 来自离子文档:

Injecting NavController will always get you an instance of the nearest NavController, regardless of whether it is a Tab or a Nav.

Behind the scenes, when Ionic instantiates a new NavController, it creates an injector with NavController bound to that instance (usually either a Nav or Tab) and adds the injector to its own providers. For more information on providers and dependency injection, see Providers and DI.

他们还说:

What if you want to control navigation from your root app component? You can't inject NavController because any components that are navigation controllers are children of the root component so they aren't available to be injected.

By adding a reference variable to the ion-nav, you can use @ViewChild to get an instance of the Nav component, which is a navigation controller (it extends NavController):

您没有可注入的 navCtrl,但您在 menu.ts :

@ViewChild(Nav) nav: Nav;

但是您在 menu.html 没有 ion-nav 作为 viewChild 您可以将 navCtrl 从 app.ts 作为输入传递给组件,或者找到一种方法将 ion-nav 包装在 menu.html 中,您也可以只在 [=23] 处声明 openPage 函数=] level,然后将其作为 Input 传递给组件(但在声明函数时使用箭头符号以保持 this 作用域)