DI problem with standalone component

This issue has been created since 2022-09-15.

Which @angular/* package(s) are the source of the bug?


Is this a regression?



I have a standalone component AppComponent and a module GuideModule and use createApplication() and @angular/elements to create custom element. I got an error when angular instantiate GuideListComponent (.in GuideModule ). Why it happens, I imported MatDialogModule in GuideModule.

@Component({ standalone: true, selector: 'pz-creator-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], encapsulation: ViewEncapsulation.ShadowDom, imports: [ CommonModule, // Features GuideModule, RouterModule, ], }) export class AppComponent implements OnDestroy {

@NgModule({ declarations: [ GuideListComponent, GuideEditorComponent, SettingsDialogComponent, ], imports: [ MatDialogModule, ], schemas: [CUSTOM_ELEMENTS_SCHEMA], exports: [], }) export class GuideModule {}

createApplication({ providers: [ INTERCEPTORS, GLOBAL_CONFIG, importProvidersFrom([ HttpClientModule, MatSnackBarModule, AppRoutingModule, BrowserModule, BrowserAnimationsModule, CampaignDataAccessModule.forRoot(), ]), ], }).then((appRef) => { const ElementConstructor = createCustomElement(AppComponent, { injector: appRef.injector, }); customElements.define('pz-creator-app', ElementConstructor); });

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(Environment Injector)[MatDialog -> MatDialog]: 
  NullInjectorError: No provider for MatDialog!
NullInjectorError: R3InjectorError(Environment Injector)[MatDialog -> MatDialog]: 
  NullInjectorError: No provider for MatDialog!
    at NullInjector.get (main.js:164607:21)
    at R3Injector.get (main.js:165110:27)
    at R3Injector.get (main.js:165110:27)
    at ChainedInjector.get (main.js:173498:32)
    at lookupTokenUsingModuleInjector (main.js:161055:31)
    at getOrCreateInjectable (main.js:161107:10)
    at Module.ɵɵdirectiveInject (main.js:169929:10)
    at NodeInjectorFactory.GuideListComponent_Factory [as factory] (main.js:872:559)
    at getNodeInjectable (main.js:161318:38)
    at instantiateRootComponent (main.js:172027:21)
    at resolvePromise (polyfills.js:1438:19)
    at resolvePromise (polyfills.js:1385:9)
    at polyfills.js:1512:9
    at ZoneDelegate.invokeTask (polyfills.js:459:171)
    at Object.onInvokeTask (main.js:187695:25)
    at ZoneDelegate.invokeTask (polyfills.js:459:54)
    at Zone.runTask (polyfills.js:220:37)
    at drainMicroTaskQueue (polyfills.js:664:23)

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 14.2.2
Node: 18.3.0 (Unsupported)
Package Manager: npm 8.11.0 
OS: darwin x64

Angular: 14.2.1
... animations, cdk, common, compiler, compiler-cli, core
... elements, forms, language-service, material
... platform-browser, platform-browser-dynamic, router
... service-worker

Package                         Version
@angular-devkit/architect       0.1402.2
@angular-devkit/build-angular   14.2.2
@angular-devkit/core            14.2.2
@angular-devkit/schematics      14.2.2
@angular/cli                    14.2.2
@angular/flex-layout            14.0.0-beta.40
@schematics/angular             14.2.2
rxjs                            7.5.4
typescript                      4.7.3

Anything else?

For a workaround, it works when I extract providers of GuideModule and add them to createApplication()

createApplication({ providers: [ INTERCEPTORS, GLOBAL_CONFIG, importProvidersFrom([ ... GuideModule, ]), ], }).then((appRef) => { const ElementConstructor = createCustomElement(AppComponent, { injector: appRef.injector, }); customElements.define('pz-creator-app', ElementConstructor); });



pkozlowski-opensource wrote this answer on 2022-09-15

Could you please create a minimal reproduce scenario in stackblitz. It is impossible to determine a root cause without a runnable reproduce scenario.

JoostK wrote this answer on 2022-09-15

This seems to be an interesting case, which I agree behaves unexpectedly.

The router creates the routed component dynamically, entering this code path:

const _injector = isComponentFactory ? contextInjector : this.parentInjector;
// DO NOT REFACTOR. The code here used to have a `injector.get(NgModuleRef, null) ||
// undefined` expression which seems to cause internal google apps to fail. This is documented
// in the following internal bug issue: go/b/142967802
const result = _injector.get(EnvironmentInjector, null);

Here, this.parentInjector is a node injector that with a the ChainedInjector of the standalone component as parent; it chains the component's environment injector (containing a provier for MatDialog) with a node injector, with the node injector being requested first.

Then, requesting the EnvironmentInjector through the ChainedInjector we end up looking in the node injector first, which arrives at the EnvironmentInjector that was used during setup of the custom element: the application injector. The standalone environment injector that contains MatDialog will not have been consulted at this point, meaning that from that moment onwards the router has created the dynamic component in the environment of the app, not of the standalone component.

I believe this is the same as, or at least very similar to, #37441 (comment). It's unfortunate that this issue still manifests itself with standalone.

More Details About Repo
Owner Name angular
Repo Name angular
Full Name angular/angular
Language TypeScript
Created Date 2014-09-18
Updated Date 2022-09-30
Star Count 84080
Watcher Count 3064
Fork Count 22235
Issue Count 1197


Issue Title Created Date Comment Count Updated Date
Inconsistent Gateway Listener Processing 4 2022-08-29 2022-09-05
Not able to Upload the .ob file which is already saved 5 2021-09-17 2022-09-03
Order of import between apollo dependencies and svelte-apollo somehow matters 2 2021-04-08 2022-09-10
Not show notification on a firebase project from git 1 2022-06-19 2022-09-09
AttributeError: 'EasyDict' object has no attribute 'depth' 2 2021-04-22 2022-09-29
Lity opens lightbox twice 4 2016-09-26 2022-09-20
Monitor refresh rate influences animation behavior (of some plugins) 3 2022-01-26 2022-08-26
作者大大,我想问一下刷了armbian的,怎么刷到openwrt或者电视盒子?armbian有点高端,玩不转,想刷回去 1 2022-07-27 2022-09-08
SSR is not working 3 2019-10-17 2022-01-14
Failed to activate the ide-python package 1 2021-07-26 2021-12-26
fix datepicker for analytics 1 2022-01-13 2022-09-12
Please Replace Youtube-dl to Yt-dlp 5 2021-10-18 2022-07-27
May I ask how to fix < AttributeError: 'NoneType' object has no attribute 'mime' > in Heroku ? 1 2021-07-17 2022-09-25
NoSuchMethodError: The method 'containsKey' was called on null (.Easy Localization) 1 2021-05-03 2022-09-22
plyr is not compatible with most recent dart sass versions 8 2021-09-17 2022-09-27
BadSpell doesn't look right when opening a file 7 2020-09-11 2022-09-23
🐞 - Fullscreen dialog has unnecessary scroll on mobile 0 2021-12-22 2022-09-28
Wrong display order on Angular 9 11 2020-03-24 2022-08-24
Excessive row heights in day grid (month view) when events are present 1 2022-05-16 2022-09-15
Voice message - unintentional draft mode 0 2021-10-08 2022-08-19
Hyperpixel 4.0 v1.3 Rock Pi Android support 0 2022-02-23 2022-09-25
Depth Picking and Render View Cross Hairs 6 2021-08-16 2022-07-20
Redir-Host 无法解析DNS 但是 Fake-IP可以 8 2022-01-30 2022-09-25
Server version unavailable 4 2019-09-25 2022-09-22
CLI hangs on "Selecting the fastest server based on ping" 14 2021-01-13 2022-09-17
Data race in github.com/pingcap/tidb/br/pkg/lightning.TestRunServer 5 2021-11-12 2022-01-29
Unresolved reference start and setListener while setting up Notification Hub 'Current SDK' 0 2021-05-19 2022-09-30
Task migration in docs 1.7.0-rc2 2 2021-10-22 2022-07-14
Apple Silicon Support 3 2021-10-27 2022-09-27
cannot get bitnami/postgresql-ha work on bare-metal server using helm 7 2022-04-29 2022-09-02
Bug: Product tour always restarts on direct message board 3 2022-03-04 2022-09-27
Beautiful UI and awsome job 1 2020-03-19 2022-09-27
Google Ads API RunTime exception 7 2022-03-07 2022-09-21
LocalDate field in Record is not properly populated by RFC3339 date string 16 2022-01-07 2022-09-01
Unable to create VPN Client configuration 6 2022-02-10 2022-09-30
之前用的是8.6版本,现在是9.1版本,排队策略问题 7 2021-05-11 2022-09-29
能否支持导出HAR文件呢? 0 2021-02-25 2022-01-16
Support the `side` property of `textPath` 0 2021-07-10 2022-09-15
Incorrect warning for unused field. 1 2022-01-17 2022-08-06
TOML dependency declaration is outdated 0 2021-09-23 2022-07-26
Feature Request: Whole-site archiving with link-rewriting to point to archived versions 3 2021-11-21 2022-08-28
X11: Allow parent window to be specified 0 2021-11-28 2022-09-21
Localization: YAML Keys, API Queries etc should not be translated 2 2021-10-24 2022-08-31
[BUG]: Java `Wait.OnSignal` does not set output coder. 0 2022-09-08 2022-09-05
[Bug] Python Mongodb IO error when loading collection with single document 4 2022-09-08 2022-09-05
[Bug]: WriteToBigQuery with file_loads and dynamic table destination doesn't load after first File Load 5 2022-09-08 2022-09-05
[Feature Request][Go SDK]: Support Slowly Changing Side Input Pattern 1 2022-09-08 2022-09-05
Filter SPI Auto Load 3 2021-10-28 2022-09-27
[Task]: Update the minor version of cloudpickle library prior to Beam release. 0 2022-09-09 2022-09-05
Argument of type 'void' is not assignable to parameter of type '(state: AppStateStatus) => void' 5 2022-02-20 2022-09-17