简体   繁体   中英

Can't able to access child component function from parent component

I have a separate assetAnnotationComponent(child) which manages the annotating functionality.This component is called from my main component to perform annotation on images by mouse events.Iam getting the following error when accessing the assetAnnotationComponent object

ERROR TypeError: Cannot read property 'mychildFunction' of undefined

I tried like following in my parent component @ViewChild(AssetAnnotationComponent) assetAnnotationComponent

Here is parent component HTML

<div class="modal-body">
  <app-asset-annotation></app-asset-annotation>
  </div>

Here is parent component typescript

import { AssetAnnotationComponent } from './asset-annotation.component';

export class ParentComponent{
@ViewChild(AssetAnnotationComponent) assetAnnotationComponent;

ngAfterViewInit(){
this.assetAnnotationComponent.mychildFunction();
}
}

my child component

export class AssetAnnotationComponent{

mychildFunction()
{
console.log("success");
}

}

I am expecting "success" to printed in console so that i can be accessing the child component's function.Thanks in advance

Edit: As suggested in comments and from the question that is suggested as duplicate, i have already tried that. I am using ngViewAfterInit for calling my function so view is loaded completely. Edit 2: My child component is from different module

Edit 2: My child component is from different module

here is my sample working code

In my code if the selector of the child component is added in parent component html then i get desired output but i need to access the child component function without adding selector of child component in parent component

in your parent component do this:

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

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

Parent HTML do this:

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

Try giving a reference to the child:

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

and then in the .ts:

@ViewChild('child') child;

then you could call it as:

this.child.mychildFunction();

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