[英]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.我需要从我的父组件调用子组件方法并且需要发送 object。 I have code below that gives me this error: Cannot read property 'RunMe' of undefined我有下面的代码给我这个错误:无法读取未定义的属性'RunMe'
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.仅供参考:如果我在 ngOnInit() 下运行 this.childComponent.RunMe() 这个 function 它可以工作。 So I dont understand what Iam doing wrong所以我不明白我做错了什么
Problem is in line window.addEventListener("message", this.displayMessage, false)
问题在于window.addEventListener("message", this.displayMessage, false)
change it to window.addEventListener("message", this.displayMessage.bind(this), false)
将其更改为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
).当您将方法作为参数传递给 function 时,它将丢失其上下文( this
)。 To enforce it's context to use our context, we use .bind()
to make it's context ( this
) explicit.为了强制使用我们的上下文,我们使用.bind()
使其上下文 ( this
) 显式。
For more info, check out https://www.javascripttutorial.net/javascript-this/有关更多信息,请查看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.第一个是:子组件位于某些结构指令下,例如 *ngIf。 here marking child as {static: false}
should fix the problem.这里将孩子标记为{static: false}
应该可以解决问题。
other case is you are using "displayMessage" method too early, when the template of your parent isn't rendered yet.另一种情况是您过早地使用“displayMessage”方法,此时您的父模板尚未呈现。 if so, put this.displayMessage(...)
call inside of ngAfterViewInit
angular lifecycle hook如果是这样,请将this.displayMessage(...)
调用放在ngAfterViewInit
angular 生命周期挂钩中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.