【发布时间】:2019-06-29 11:26:46
【问题描述】:
我有一个单独的assetAnnotationComponent(child) 来管理注释功能。这个组件是从我的主组件中调用的,以通过鼠标事件对图像执行注释。访问assetAnnotationComponent 时出现以下错误对象
ERROR TypeError: Cannot read property 'mychildFunction' of undefined
我尝试在我的父组件中进行如下操作
@ViewChild(AssetAnnotationComponent) assetAnnotationComponent
这里是父组件 HTML
<div class="modal-body">
<app-asset-annotation></app-asset-annotation>
</div>
这是父组件的打字稿
import { AssetAnnotationComponent } from './asset-annotation.component';
export class ParentComponent{
@ViewChild(AssetAnnotationComponent) assetAnnotationComponent;
ngAfterViewInit(){
this.assetAnnotationComponent.mychildFunction();
}
}
我的子组件
export class AssetAnnotationComponent{
mychildFunction()
{
console.log("success");
}
}
我希望在控制台中打印“成功”,以便我可以访问子组件的功能。提前致谢
编辑: 正如 cmets 中的建议和建议为重复的问题,我已经尝试过了。我正在使用 ngViewAfterInit 调用我的函数,以便完全加载视图。 编辑 2:我的子组件来自不同的模块
编辑 2:我的子组件来自不同的模块
here is my sample working code
在我的代码中,如果子组件的选择器被添加到父组件 html 中,那么我会得到想要的输出,但是我需要访问子组件函数而不在父组件中添加子组件的选择器
【问题讨论】:
-
这是
ParentComponentHTML 的全部吗?或者父 HTML 有没有*ngIf或者类似的条件渲染逻辑? -
您似乎在模态中拥有
AssetAnnotationComponent,您可能有条件地在ParentComponent中显示。因此,您没有通过 ViewChild 在 ParentComponent 中获得对它的引用。因此出现错误。 -
您将在the duplicate question 中找到两种可能的解决方案:(1) 使用
ViewChildren和QueryList.changes,(2) 使用ViewChild的setter。 -
同样,如果它不存在于组件的模板中,则它不是子组件。所以,你不能使用
ViewChild。
标签: angular typescript viewchild