繁体   English   中英

Angular 2-无法使用ViewChild或ContentChild获得基类实例

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

回答:

  • 不要使用exportAs

  • 使用@ViewChild('myContent')myContent; 获取父类的实例

  • 它仅在视图初始化时才起作用,因此最好使用ngAfterViewInit


这关系到继承!

base class (component)
    |
inherited class (component)

我有一个用exportAs导出的基类组件

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

继承的类组件在其自己的模板中使用对基类模板的引用

<my-content #myContent>
  ...

在继承的组件的代码中,我尝试获取其实例

@ViewChild('myContent') myContent;

要么

@ContentChild('myContent') myContent;

有人说这应该工作,但myContent始终未定义

我该如何解决?

谢谢

要在父模板中获取子组件的实例,可以直接使用Component类,而无需任何引用,例如

@ViewChild(MyComponentClass) myContent; 

其中MyComponentClass是子组件类的导出名称。

附带说明一下,请确保在检查/初始化视图之后(使用ngAfterViewInit )而不是在ngOnInit上引用了myComponent变量,因为在初始化阶段,尚未创建子组件。

这是一个工作的朋克:

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

@ViewChild(MyParentComponent) myParent: MyParentComponent

你可以实例的父组件一样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); 
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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