简体   繁体   中英

Angular 2 - cannot get base class instance with ViewChild nor ContentChild

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

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM