![](/img/trans.png)
[英]Angular2 Components :: ViewChild / ContentChild by class
[英]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
变量,因为在初始化阶段,尚未创建子组件。
这是一个工作的朋克:
@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.