[英]Ionic 2 - ViewChild component is undefined
THE SITUATION : 情况 :
From the app component I need to call a method in another component. 从app组件我需要在另一个组件中调用一个方法。
I read that @ViewChild
is the way to do it. 我读到
@ViewChild
就是这样做的。
But is not working in my case. 但是我的情况不适用。 I am getting the following error:
我收到以下错误:
Cannot read property ... of undefined
THE CODE : 代码 :
This for example is a simple test method inside the HomePage component : 例如,这是HomePage组件中的一个简单的测试方法:
testChild()
{
alert('child working');
}
In the app.component I declare HomePage as the child component: 在app.component中,我将HomePage声明为子组件:
@ViewChild(HomePage) homePage: HomePage;
and then call the method from the constructor: 然后从构造函数中调用该方法:
this.homePage.testChild();
It should work right? 它应该工作正常吗?
Instead I am getting this error: 相反,我收到此错误:
The problem is not that the view is not loaded yet. 问题不在于视图尚未加载。
I have tried also to call the child from a click event and got the same error. 我也试过从点击事件中调用孩子并得到同样的错误。
THE QUESTION : 问题 :
Why is the child component is undefined? 为什么子组件未定义?
Do you know what am I doing wrong? 你知道我做错了什么吗?
Thanks! 谢谢!
and then call the method from the constructor:
然后从构造函数中调用该方法:
You need to call it in the ngAfterViewInit
lifecycle hook. 您需要在
ngAfterViewInit
生命周期钩子中调用它。 Angular will call the method. Angular将调用该方法。
import { AfterViewInit } from '@angular/core';
@Component()
export class MyComponent implements AfterViewInit {
@ViewChild(HomePage) homePage: HomePage;
ngAfterViewInit() {
this.homePage.testChild();
}
}
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.