2016-11-28 81 views
3

局势离子2 - ViewChild成分是未定义

从应用程序部件我需要调用在另一部件的方法。

,我读了@ViewChild是做它的方式。

但不是在我的情况下工作。我得到以下错误:

Cannot read property ... of undefined 

THE CODE

这例如是主页部件内一个简单的测试方法:

testChild() 
{ 
    alert('child working'); 
} 

应用程序。组件我声明HomePage作为子组件:

@ViewChild(HomePage) homePage: HomePage; 

,然后调用从构造方法:

this.homePage.testChild(); 

它应该工作的权利?

相反,我得到这个错误:

enter image description here

的问题不是该视图尚未加载。

我曾尝试也叫从click事件的孩子,并得到了同样的错误。

问题

为什么子组件是不确定的?

你知道我在做什么错?

谢谢!

+0

你能分享更多的代码,你app.component好吗?例如,你在哪里调用这个方法。 – echonax

+0

我们将需要查看您的app.component html – PierreDuc

回答

2

and then call the method from the constructor:

您需要在ngAfterViewInit生命周期挂钩中调用它。 Angular会调用这个方法。

import { AfterViewInit } from '@angular/core'; 

@Component() 
export class MyComponent implements AfterViewInit { 

    @ViewChild(HomePage) homePage: HomePage; 

    ngAfterViewInit() { 
    this.homePage.testChild(); 
    } 
} 

参见:

+0

感谢您的回复。但还没有工作。同样的错误。无论我从哪里调用它,错误都是一样的。 – johnnyfittizio

+0

@johnnyfittizio是模板中的主页组件吗?这就是@ @ ViewChild'用于 –

+0

Yes HomePage是根组件,并且被导入到app.component中。app.html是一个双菜单,在右侧菜单中有一个登录表单。表单正在工作,所有的登录都在app.component中。在app.component表单提交功能里,我只需要调用homePage组件的一个方法。 – johnnyfittizio