1

answer:

  • dont use exportAs

  • use @ViewChild('myContent') myContent; to get the instance of the parent class

  • it will only work if the view is initialized, so better use ngAfterViewInit


this concerns inheritance !

base class (component)
    |
inherited class (component)

I have a base class component exported with exportAs

@Component({
    selector: 'my-content',
    exportAs: 'myContent',
    ...
})

the inherited class component uses a reference to the base class template in its own template

<my-content #myContent>
  ...

in the inherited component's code I try to get its instance

@ViewChild('myContent') myContent;

or

@ContentChild('myContent') myContent;

some say this should work but myContent is alway undefined

how do I solve this ?

thanks

1
  • Can you reproduce in Plunker? Commented Aug 30, 2017 at 6:44

2 Answers 2

1

To get the instance of the child component within the parent template you can use the Component class directly, without any references, like so

@ViewChild(MyComponentClass) myContent; 

Where MyComponentClass is the exported name of the child component class.

As a side note, make sure that you are referenceing the myComponent variable after the views have been checked / initialized (using ngAfterViewInit) rather than on ngOnInit, since during the init stage, the child components would not have been created yet.

Here's a working plunkr :

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

Sign up to request clarification or add additional context in comments.

3 Comments

it's the other way around, I want to call the parent function from the child
I tried with ngAfterViewInit instead of ngOnInit but still the reference in undefined
Fixed your plunkr to work. Changed ContentChild to ViewChild, and removed the exportAs decleration.
0

@ViewChild(MyParentComponent) myParent: MyParentComponent

you can instance the Parent Component like this.myParent

plunker:

import { Component, ViewChild } from '@angular/core';

@Component({...})

export class InheritedComponent extends BaseClassComponent {  

    @ViewChild(BaseClassComponent) myBaseclass: BaseClassComponent;

    doSomeOperations()
    {
        this.myBaseclass.toggle();
        console.log(this.visible); 
    }

}

4 Comments

then why calling the variable myChild ? it should be myParent or something.I tried your solution, it does not work
still the reference in undefined ?
I'm getting True in console. UPDATED
you should get FALSE I already tried that, does not work it gives UNDEFINED for the baseClass variable.. I updated the plunker plnkr.co/edit/jjN9An8G2QKzqFqk3dnp?p=preview you can see for yourself I tried in Chrome and Firefox

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.