3

Not really sure how to explain this but i will give my best shot.

I have an injectable provider that is bootstrapped in the main app. The provider its trying to access a component.

I can access that component using ViewChild from other components, but i cannot from the injectable provider. I think its because the provider its initialized before the component, so its not available to the ViewChild query.

Is there a method to use the Viewchild reference from inside the injectable function? Something like initialize the children when i am calling the function.

Sorry if this is confusing, not really sure how to explain.

Thanks, Radu

keepwalking
  • 2,644
  • 6
  • 28
  • 63

1 Answers1

1

@ViewChild() queries the view. An injectable (service) doesn't have a view, therefore @ViewChild() can't find one. Also Angular doesn't process @ViewChild() annotations in services in the first place, only in directives and components.

What you can do is to query using @ViewChild() and pass the result to a shared service.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Right now my workaround is to have a public variabile inside the service and i am just setting that in the afterViewInit function and its available to me afterwards. I just tough it will be a cleaner way for it. Thanks for the explanation – keepwalking Jun 07 '16 at 15:30
  • I'd consider it bad design to have a `@ViewChild()` (`ElementRef`) or whatever it returns in a service anyway. I'd rather use a service to communicate with the component that contains the `@ViewChild()` to make the component execute commands against the reference instead of passing the reference around. – Günter Zöchbauer Jun 07 '16 at 15:35
  • Any indications on how can i make the service communicate with the component? – keepwalking Jun 07 '16 at 15:37
  • Thanks for the tutorial. If i have 2 components that are not in the same html tree do i have to use a service for reference right? – keepwalking Jun 08 '16 at 06:42
  • Not sure what you mean by "not in the same html tree". Maybe like http://stackoverflow.com/questions/36566698/cant-initialize-dynamically-appended-component-in-angular-2/36566919?noredirect=1#comment60736661_36566919 with two independently bootstrapped Angular2 applications? If both components are in the same Angular application you can define the scope of the shared service by where you add it as provider. It needs to be a common parent. The root component is a common parent of all components in your Angular2 application. – Günter Zöchbauer Jun 08 '16 at 06:45
  • The thing is that i am using Ionic 2 witch bootstraps the app automatically. Please refer to http://stackoverflow.com/questions/37695386/ionic-2-getcomponent-alternative if you know about Ionic 2. – keepwalking Jun 08 '16 at 07:02