2016-11-28 78 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