Alex Weber
Alex Weber

Reputation: 2186

Access child component's providers in Angular2

Say I have a component which uses a 3rd party component from Github which defines it's own providers.

<my-component>
    <awesome-contrib-component></awesome-contrib-component>
</my-component>

and for the awesome-contrib-component providers:

@Component({
    selector: 'awesome-contrib-component',
    providers: [FooProvider]
})

As far as I can tell, even if I provide FooProvider at the app bootstrap level or even on my-component (with either providers or viewProviders), since awesome-contrib-component specifies it's own providers, it's always getting it's own instance.

The problem is that in my-component I need access to the same instance of FooProvider that is used byawesome-contrib-component and I'm not able to get it.

Is this possible at all? Am I missing something? Thanks!

The important thing to stress here is that awesome-contrib-component is a 3rd party module from Github, it defines it's own providers and assigns FooProvider to itself as a private variable and doesn't expose it.

As someone using this 3rd-party library short of opening a PR (which I did) I'm not sure how to work around this.

Upvotes: 2

Views: 2196

Answers (2)

Tiberiu Popescu
Tiberiu Popescu

Reputation: 4524

You are definitely missing something, yes ! :)

So if you want the same provider instance into the child and the parent, then you just provide it in the parent component(NOT in the child), in the child you just use it (without provide) so you will have the same instance.

More on providers/dependency injection/ services : https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

Upvotes: 2

Ankit Singh
Ankit Singh

Reputation: 24945

Use @ViewChild, or if you have multiple children use @Children, like this

@Component({
    selector: 'my-component',
    directives: [AwesomeContribComponent]
})
export class MyComponent{
  @ViewChild(AwesomeContribComponent) public childInstance: AwesomeContribComponent

  ngAfterViewInit(){
     console.log(this.childInstance.fooProvider); // you got the service
  }

}

@Component({
    selector: 'awesome-contrib-component',
    providers: [FooProvider]
})
export class AwesomeContribComponent {
  constructor(public fooProvider: FooProvider){}
}

Upvotes: 3

Related Questions