参考ViewChild内容Angular2

时间:2016-08-10 11:22:11

标签: angular typescript ionic2

我在 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:无法读取未定义的属性“type”

如何从我的指令访问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中无效。我收到以下错误:

  

提供的参数与呼叫目标的任何签名

都不匹配

enter image description here

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

2 个答案:

答案 0 :(得分:2)

ngAfterViewInit hook

中试用
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

答案 1 :(得分:0)

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

所以在你的页面中,你有:

@ViewChild(Content) content: Content;

您的标题如下所示:

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

然后在你的指令类中:

@Input('yourDirective') content: Content;
相关问题