dag dag - 3 months ago 424
TypeScript Question

Reference ViewChild content Angular2

I create a directive in Angular 2 and in this directive I have to access

Component
. For that I used the
ViewChild
(this approach worked in normal component, but it is not working in the directive context.

That is my directive:

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


In the
console.log
I get the following exception:


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


How can I access
Component
from my directive?

EDIT:

Unfortunately I've pasted the wrong code in here, but still the same problem.

I need to get
Content
and not
Component
as mentioned.

So here is the code.
Content
is still undefined:

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


EDIT:

I created a Plunker with the code, check the console and you will see undefined

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

Answer

Try it within ngAfterViewInit hook

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

Update:

You can use Host decorator to do that:

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

Comments