参考 ViewChild 内容 Angular2

Reference ViewChild content Angular2

我在 Angular 2 中创建了一个指令,在这个指令中我必须访问 Component。为此,我使用了 ViewChild(这种方法在普通组件中有效,但在指令上下文中无效。

这是我的指令:

import {Component, ViewChild} from "@angular/core";
import {NavController, NavParams} from "ionic-angular";
import {IONIC_DIRECTIVES} from "ionic-angular";
import {ComponentBase} from "../../component.base";

@Component({
    selector: "header-content",
    directives: [IONIC_DIRECTIVES],
    templateUrl: "build/pages/components/header-content/header.content.html"
})
export class HeaderContentComponent {
    @ViewChild(Component) protected component;

    constructor() {
        console.log(this.component.type);
    }
}

console.log 我得到以下异常:

EXCEPTION: TypeError: Cannot read property 'type' of undefined

如何从我的指令访问 Component

编辑:

不幸的是,我在这里粘贴了错误的代码,但仍然是同样的问题。

我需要 Content 而不是上面提到的 Component

这是代码。 Content 仍未定义:

import {Component, ViewChild} from "@angular/core";
import {NavController, NavParams, Content} from "ionic-angular";
import {IONIC_DIRECTIVES} from "ionic-angular";
import {ComponentBase} from "../../component.base";

@Component({
    selector: "header-content",
    directives: [IONIC_DIRECTIVES],
    templateUrl: "build/pages/components/header-content/header.content.html"
})
export class HeaderContentComponent {
    @ViewChild(Content) protected content: Content;

    public toolbarActive: boolean = false;

    public toggleToolbar() {
        this.toolbarActive = !this.toolbarActive;

        if (this.toolbarActive) {
            // this.content.removeCssClass("no-scroll");
            // this.content.addCssClass("scroll");
        } else {
            // this.content.removeCssClass("scroll");
            // this.content.addCssClass("no-scroll");
        }

        // this.content.resize();
    }

    protected ngAfterViewInit() {
        console.log(this.content);
    }
}

编辑:

我用代码创建了一个 Plunker,检查控制台,你会看到 undefined

https://plnkr.co/edit/ayFskPyDRlpYDkMEapDL?p=preview

编辑:

接受下面的答案后(它适用于 Plunker),但它在我的 Visual Studio 中不起作用。我收到以下错误:

Supplied parameters do not match any signature of call target

新 Plunker:https://plnkr.co/edit/ayFskPyDRlpYDkMEapDL?p=preview

ngAfterViewInit 挂钩中尝试

ngAfterViewInit() {
  console.log(this.component.type);
}

更新:

您可以使用 Host 装饰器来做到这一点:

import {Component, ViewChild, Host} from "@angular/core";
import {Content, IONIC_DIRECTIVES} from "ionic-angular";

@Component({
    selector: "hello-world",
    directives: [IONIC_DIRECTIVES],
    templateUrl: 'src/hello-world.html'
})
export class HelloWorld {
  constructor(@Host(Content) private content: Content) {
    console.log(this.content);
  }
}

Plunker

您可以将页面中的 @ViewChild(Content) 作为指令输入传递到 ion-header。

因此在您的页面中,您有:

@ViewChild(Content) content: Content;

您的 header 看起来像:

<ion-header [yourDirective]="content">

然后在你的指令中 class:

@Input('yourDirective') content: Content;