How to provide an instance oer each child component?

Viewed 2578

I'm getting familiar with how dependency injection works in Angular 2, but I'm trying to figure out if a specific use case is possible.

In short I'd like to have a child component that has a dependency injected like so:

@Component( {
    selector: 'child',
    template: `
        <div class="child">
            <span><a href="#" (click)="idService.regenerate()">Regenerate</a></span>
            <span>{{idService.id}}</span>
        </div>
    `
})
export class ChildComponent {

    constructor(
        protected idService: IdService
    )
    {}
}

At higher levels of my component tree I am using providers: [IdService] to inject different instances of the service. This all makes sense and doesn't give me a problem. However, what I'd like to understand is if this is possible without creating a "copy" of the child component with its own providers: [...] property in the component annotation:

https://plnkr.co/edit/ZMYNIH7lB0Oi6EBSYmfB?p=preview

In that example you'll see the bottom set of components each get a new instance of the IdService class, but it's because they're really a new component that specifically requests a new instance.

What I'd like to know is if there's a way to achieve this simply with the parent component? Like being able to say "give a new instance each time a child component tries to resolve this specific dependency"?

2 Answers
Related