简体   繁体   中英

Calling Child Component Method From Parent Methods Angular 8

I need to call child component method from my parent component and need to send object. I have code below that gives me this error: Cannot read property 'RunMe' of undefined

what I am missing?

child component:

runMe = (item)  => {
    this.cdr.detectChanges();
    if (item.hidden) {
        this.showErrorMsgEvent.emit();
    } else {
        this.highLightEvent.emit(item);
    }
}

Parent:

@ViewChild(childComponent, { static: true }) childComponent;

ListenIframeEvents(){
    window.addEventListener("message", this.displayMessage, false)
  }
  displayMessage (item) {
    this.childComponent.RunMe(item)
  }


<child-component #childComponent></child-component>

I have googled and most answers suggesting adding the # selector but that does not work for me.

FYI: if I run this.childComponent.RunMe() this function under the ngOnInit() it works. So I dont understand what Iam doing wrong

Problem is in line window.addEventListener("message", this.displayMessage, false)

change it to window.addEventListener("message", this.displayMessage.bind(this), false)

UPDATE:

When you pass a method to a function as a parameter, it will lose it's context ( this ). To enforce it's context to use our context, we use .bind() to make it's context ( this ) explicit.

For more info, check out https://www.javascripttutorial.net/javascript-this/

there are 2 possible issues here.
the 1st one is: child-component lies under some stuctural directives like *ngIf. here marking child as {static: false} should fix the problem.
other case is you are using "displayMessage" method too early, when the template of your parent isn't rendered yet. if so, put this.displayMessage(...) call inside of ngAfterViewInit angular lifecycle hook

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