FrancescoMussi
FrancescoMussi

Reputation: 21610

Ionic 2 - ViewChild component is undefined

THE SITUATION:

From the app component I need to call a method in another component.

I read that @ViewChild is the way to do it.

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:

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

In the app.component I declare HomePage as the child component:

@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:

enter image description here

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!

Upvotes: 3

Views: 6261

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208994

and then call the method from the constructor:

You need to call it in the ngAfterViewInit lifecycle hook. Angular will call the method.

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

@Component()
export class MyComponent implements AfterViewInit {

  @ViewChild(HomePage) homePage: HomePage;

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

See also:

Upvotes: 3

Related Questions