Angular use multiple instances of service of parent component to child

Viewed 1161

I've seen this thread: Using multiple instances of the same service. Is it possible to use same multiple instance of a service from parent to children?

For example, I have an ElementService in ParentComponent and have 2 instances of that service

{ provide: 'instance1', useClass: ElementService},
{ provide: 'instance2', useClass: ElementService},

How should I use instance1 in Child1Component and instance2 in Child2Component?

2 Answers

When you specify providers in a component's decorator, the providers that are injected become specific to that component see Angular - Providing dependencies

This is also helpful info about dependency injection

So just specify the service in both of the component's providers array and you should have unique instances of the service in both components.

@Component({
    selector: 'app-page',
    templateUrl: './page.component.html',
    styleUrls: ['./page.component.scss'],
    providers: [
        ElementService
    ]
})
export class PageComponent implements OnInit {...
Related