Search code examples
angulartypescriptangular-routingangular-moduleangular-lazyloading

Does importing a component from a lazy loaded module elsewhere in the app circumvent lazy loading of this module in Angular 12?


We have some modules that come with their own navigation bars. These nav bars are actual components and they activated in the global HeaderComponent of the app as soon as the corresponding route is activated.

To pass the navigation component we use the dataproperty of the route in app-routing.module.ts:

import { TestNavigationComponent } from './modules/test/components/test-navigation/test-navigation.component';

{
  path: 'test',
  loadChildren: () => import('./modules/test/test.module').then(m => m.TestModule),
  data: {
    nav: TestNavigationComponent
  },
},

While this works fine, I wonder:

Does this circumvent lazy loading of the module? Is the module loaded anyway, because the navigation component is imported in the gobal app-routing.module.ts already?

If yes, how could I bundle the navigation component along with the module and pass it to the application's header?

The naviagtion is rendered in the header component like this currently:

private updateNavigation(snapshot: ActivatedRouteSnapshot): void {
  const nav: Type<Component> = (snapshot.data as {nav: Type<Component>}).nav;

  if (nav instanceof Type) {
    if (nav === this.navigationType) {
      return;
    }

    this.clearNavigation();
    this.navigationType = nav;

    const factory: ComponentFactory<Component> = this.componentFactoryResolver.resolveComponentFactory(nav);
    this.navigationComponentRef = this.navigationRef.createComponent(factory);

    return;
  }

  for (let childSnapshot of snapshot.children) {
    this.updateNavigation(childSnapshot);
  }
}

Solution

  • I'm not sure exactly the reason you're passing the component itself rather than a string, which would allow you inside the module to just use a switch statement to give the correct component.

    For visualizing what ends up in each module the --stats-json option for ng build is invaluable.

    You can check to see where your components ended up with webpack-bundle-analyzer using the command

    npx webpack-bundle-analyzer dist/APPNAME/browser/stats.json
    

    That would (for this case) show your component in your main bundle.


    I misunderstood your question at first but I'll leave this here as an aside:

    You can now lazy load just components (if they are standalone) in Angular 14 and above.

    {
       path: 'faq',
       loadComponent: () => import('./lazy-faq-dialog/lazy-faq-dialog.component').then(m => m.LazyFaqDialogComponent)
    }