【问题标题】:Can't able to access child component function from parent component无法从父组件访问子组件功能
【发布时间】: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 中,那么我会得到想要的输出,但是我需要访问子组件函数而不在父组件中添加子组件的选择器

【问题讨论】:

  • 这是ParentComponent HTML 的全部吗?或者父 HTML 有没有 *ngIf 或者类似的条件渲染逻辑?
  • 您似乎在模态中拥有AssetAnnotationComponent,您可能有条件地在ParentComponent 中显示。因此,您没有通过 ViewChild 在 ParentComponent 中获得对它的引用。因此出现错误。
  • 您将在the duplicate question 中找到两种可能的解决方案:(1) 使用ViewChildrenQueryList.changes,(2) 使用ViewChild 的setter。
  • 同样,如果它不存在于组件的模板中,则它不是子组件。所以,你不能使用ViewChild

标签: angular typescript viewchild


【解决方案1】:

在你的父组件中这样做:

@ViewChildren('myChild') assetAnnotationComponent: QueryList<AssetAnnotationComponent>; 
public currentChildComponent: AssetAnnotationComponent;

    ngAfterViewInit(): void {
          this.assetAnnotationComponent.changes.subscribe(data => {
              this.currentChildComponent= data._results[0];
              this.currentChildComponent.mychildFunction();
          });
    }

父 HTML 这样做:

<div class="modal-body">
  <app-asset-annotation #myChild></app-asset-annotation>  //notice the template variable
</div>

【讨论】:

    【解决方案2】:

    尝试引用孩子:

    <app-asset-annotation #child></app-asset-annotation>
    

    然后在 .ts:

    @ViewChild('child') child;
    

    那么你可以这样称呼它:

    this.child.mychildFunction();
    

    【讨论】:

    • 我已经试过了,但是没有用。谢谢你的回复@fisnik
    • 我意识到动态创建的孩子需要它。似乎@Nadhir 的回答可以解决这个问题!
    • 我测试了 ViewChildren 方法并在按钮单击时动态添加了 childrenComponents,它可以工作!
    • 我已经编辑了我的问题我忘了提到我的子组件来自不同的模块@Fisnik
    • 正如我在上面的cmets中所说,我用来测试的代码来自@Nadhir Falta的回答,你可以试一试!
    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2021-10-27
    • 2016-06-02
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多