Skip to content

Injection Context for loadChildren and loadComponent functions #51532

Closed

Description

@IKatsuba

Which @angular/* package(s) are relevant/related to the feature request?

router

Description

What I have

  • host application
  • micro front-end applications that are loaded using loadChildren and loadConponent
  • localization using @angular/localize

Problem

Need to load micro-frontend module or component with host application locale.

The LOCALE_ID token is used to determine the current locale. The first thing that comes to mind is to use the inject function to get the token value from the injector.

{
  path: '...',
  loadChildren: () => loadRemoteModule(`module-${inject(LOCALE_ID)}`, 'Module')
}

But in the loadChildren and loadComponent functions, using the inject function causes an error.

NG0203: `inject()` must be called from an injection context, such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`.

Proposed solution

I propose to create an injection context for loadChildren and loadComponent functions when calling them

Alternatives considered

I am setting the locale to the window object as a fast solution.

{
      provide: APP_INITIALIZER,
      multi: true,
      useFactory: () => {
        const locale = inject(LOCALE_ID);
        const windowRef = inject(WINDOW);

        windowRef.__LOCALE_ID__ = AvailableLocales.includes(
          locale as AvailableLocale
        )
          ? locale
          : AvailableLocale.EN;
        return () => undefined;
      },
    }

And then load micro-frontend:

{
  path: '...',
  loadChildren: () => loadRemoteModule(
    `module_${window.__LOCALE_ID__}`,
    moduleName
  )
}

But for SSR, I will have to get another solution.

Activity

  1. added
    feature
    on Aug 28, 2023
  2. angular-robot commented on Aug 28, 2023

    @angular-robot
    Contributor

    This feature request is now candidate for our backlog! In the next phase, the community has 60 days to upvote. If the request receives more than 20 upvotes, we'll move it to our consideration list.

    You can find more details about the feature request process in our documentation.

  3. added this to the Backlog milestone on Aug 28, 2023
  4. added
    feature: under consideration
    and removed on Aug 31, 2023
  5. Erbenos commented on Oct 11, 2023

    @Erbenos
    Contributor

    Alternatively one could setup routes by providing the ROUTES DI token manually via a factory function. In that factory function you can use inject and hence you can build the remote module's path dynamically.

  6. chriswoodie commented on Jan 4, 2024

    @chriswoodie

    This is crucial to let developers translate the paths of lazy loaded routes in applications that depend on SSR. Since the @angular/localize package doesn't provide any out-of-the-box solution for this, one must get hold of the lang via document.documentElement.lang (since it's set automatically when using different locales) and iterate over the routes and their children to change the paths. However, for that you need to inject DOCUMENT, which you can't, and there's no way of getting a workable injector in this context.

    Example of this:

    export const appRoutes: Route[] = [
      {
        path: '$testing', // Gets replaced with the actual route path that exists in the translation file for the active locale
        loadChildren: () => import('./views/testing/testing.routes').then(m => {
        
          const lang = inject(DOCUMENT).documentElement.lang; // Currently breaks
          
          return translateRoutes(m.testingRoutes, lang);
        }),
      },
    ...
    ];
    

    Please implement this 🙏

  7. Ketec commented on Feb 20, 2024

    @Ketec

    It is also important for dynamic routes, especially with standalone components where you no longer have modules for each component.

    I even tried with ENVIRONMENT_INITIALIZER + router.resetConfig (but it gives root routes where the current lazy child is not accessible to modify/add children to).

    Can it pass injector to all the child routes when you configure it at the root?

    Is there a chance it makes it into 17.x.x or more likely 18+?
    Or is there even any idea/plan as to how this could be achieved?

  8. Erbenos commented on Feb 20, 2024

    @Erbenos
    Contributor

    For such dynamic routes, you may instead want to provide ROUTES token manually through factory function. Refer to provideRouter at

    export function provideRouter(routes: Routes, ...features: RouterFeatures[]): EnvironmentProviders {

  9. Ketec commented on Feb 20, 2024

    @Ketec

    The dynamic routes are needed for the lazy loaded child route (where previously that component module could use ROUTES token to map new children) but as mentioned in the closed bug ticket - this no longer works with standalone.

    ROUTES factory is never called even if it's in the component routes.ts as providers.

    looking at angular code:

    return wrapIntoObservable(route.loadChildren!()).pipe(

    It looks to me as if injector, route are passed to the loadChildren?

    Making sure these are available in the callback too would likely solve these issues.

  10. Erbenos commented on Feb 20, 2024

    @Erbenos
    Contributor

    I see. Perhaps you would be able to get hold of nearest injector through ENVIRONMENT_INITIALIZER like this? https://stackblitz.com/edit/stackblitz-starters-tayqtx?file=src%2Fmain.ts I mean its ugly, but it gets the job done. This isn't really a first case when it would be handy to get the routerConfig callbacks ran within an injection context, another I can think of is #53944

  11. Ketec commented on Feb 21, 2024

    @Ketec

    ENVIRONMENT_INITIALIZER is not available in component providers. It is there in the route.ts (for the component), but you can't store local variables there.

    It wouldn't be at the initial bootstrap either, but somewhere deeper (some child module routes).

    export const routes: Routes = [
      {
        path: '',
        component: TestComponent,
        providers: [
          {
            provide: ROUTES, // ENVIRONMENT_INITIALIZER
            multi: true,
            useFactory: () =>...
          }
        ]
      }
    ];
    

    Which is the "new" pattern to route to standalone components without modules.

    ROUTES does not work here either anymore. ENVIRONMENT_INITIALIZER does - but can't store local variables.
    Can't modify the child routes (resetRouter) in ENVIRONMENT_INITIALIZER since the loadChildren import content for this route is not a static list of children, and the subroutes are not yet available.

  12. Erbenos commented on Feb 21, 2024

    @Erbenos
    Contributor

    See #54518 (comment), you don't need to put route subtrees into component providers. Instead, declare them outside the component providers and load just route definitions. I know you have to save the reference to injector manually, thats why I said its ugly. I am only offering a workaround here. As for the modifying the child route configs, I am not familiar with that, however the stackblitz concept I linked should allow you to setup route subtrees in dynamic manner when the tree is being resolved in at least some capacity.

  13. Ketec commented on Feb 21, 2024

    @Ketec

    https://stackblitz.com/edit/stackblitz-starters-fjgpj5?file=src%2Flazy-page%2Froutes.ts

    An example. The lazy-page/routes.ts for reference would need dynamic children.

    This cannot be done at the root bootstrap level. Bootstrap should not contain any code specific to that sub-component/micro module.

  14. Erbenos commented on Feb 21, 2024

    @Erbenos
    Contributor

    The problem in your linked stackblitz is exactly something that the concept in stackblitz I linked allows you to work around.

  15. Char2sGu commented on Jun 29, 2024

    @Char2sGu
    Contributor

    This has the potential to enable async providers for child routes by invoking a request with HttpClient and configure the child route's provider property according to the request.

  16. Char2sGu commented on Jul 26, 2024

    @Char2sGu
    Contributor

    In case anyone is looking for an out-of-box workaround:

    /**
     * Workaround to emulate an injection context in the route's loadChildren resolver.
     * @param route
     * @returns
     * @see https://github.com/angular/angular/issues/51532#issuecomment-1956138610
     */
    export function setupInjectionContextForLoadChildren(route: Route): Route {
      let injector: Injector | undefined = undefined;
      const injectorInitializerProvider: Provider = {
        provide: ENVIRONMENT_INITIALIZER,
        multi: true,
        useFactory:
          (instance = inject(Injector)) =>
          () => {
            injector = instance;
          },
      };
    
      const transformRoute = (child: Route) => {
        if (!child.loadChildren) return child;
        const loadChildren = child.loadChildren;
        child.loadChildren = (...args) => {
          if (!injector) throw new Error('Missing injector');
          return runInInjectionContext(injector, () => loadChildren(...args));
        };
        return child;
      };
    
      return {
        path: '',
        providers: [injectorInitializerProvider],
        children: [transformRoute(route)],
      };
    }
    export const APP_ROUTES: Routes = [
      setupInjectionContextForLoadChildren({
        path: '',
        loadChildren: async (providersLoader = inject(MyProvidersLoader)) => [
          {
            path: '',
            providers: await providersLoader.load(),
            component: MyComponent,
          },
        ],
      }),
    ];
  17. JSProto commented on Sep 20, 2024

    @JSProto

    How do you like this solution?
    Way of getting a workable injector in this context.

    export function loadChildren(useFactory: () => Route[]): LoadChildren {
      @NgModule({
        imports: [RouterModule.forChild([])],
        providers: [{ provide: ROUTES, useFactory, multi: true }],
      })
      class ProxyRoutingModule {}
    
      return () => ProxyRoutingModule
    }

    routes.ts

    export const routes: Routes = [
      {
        path: '',
        component: TestComponent,
        loadChildren: loadChildren(() => {  
            const lang = inject(DOCUMENT).documentElement.lang;
            const routes = inject(MY_TOKEN_WITH_ROUTES, {optional: true}) || []
            return [...routes, /** and dynamic routes */ ]
        })
      }
    ];
  18. added 3 commits that reference this issue on Jun 17, 2025
    3502542
    f1d52cc
    593a85b
  19. added a commit that references this issue on Jun 24, 2025
    9833d9e
  20. angular-automatic-lock-bot commented on Jul 25, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  21. locked and limited conversation to collaborators on Jul 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: routereffort1: hoursfeaturefeature: under considerationrouter: lazy loading

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions