gök
gök

Reputation: 49

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

Upvotes: 0

Views: 531

Answers (2)

R Pasha
R Pasha

Reputation: 710

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/

Upvotes: 1

Andrei
Andrei

Reputation: 12206

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

Upvotes: 0

Related Questions