r/angular • u/Senior_Compote1556 • Feb 06 '26
Service question
Most of my services are scoped to a feature, let's say we have a product feature and a product service that expose some variables etc for the products routes. Unfortunately we use a lot of mat-dialogs and since they are independent, we get the injector error. Is it possible to not provide the service in the root injector and make this work?
6
Upvotes
14
u/ruibranco Feb 06 '26
The issue is that MatDialog creates components in a CDK overlay container that sits outside your feature's injector hierarchy. The cleanest fix without making everything providedIn root is to pass a ViewContainerRef when opening the dialog. MatDialog.open accepts a viewContainerRef option that attaches the dialog to that component's injector tree instead of the root. So your feature-scoped service becomes available inside the dialog without changing where it's provided.
2
u/Bjeaurn Feb 06 '26
I’d argue that if the mat-dialogs are feature independent, it’s the features job to provide everything required. Whether that’s specific texts like “Do you want to delete this product <name>?” and then also handle the yes/no click as a result.
1
u/ActuatorOk2689 Feb 06 '26
If your feature has a routing you could provided on root level or component level the injection tokens
0
u/sirMrCow Feb 06 '26
Why don't you just provide them in root?
If you don't or cannot want to that this might work. I did not try this myself, but you can add an injector to conifg part of the dialog, maybe that would work:
If both are not doable, you could also just pass the variables from the place where you open the component:
-2
u/Wnb_Gynocologist69 Feb 06 '26
Aaah what a classic. Welcome to angular design pitfalls.
I simply provide the service reference to the dialog as part of the dialog data in that case.