Home > database >  angular load modules based on url
angular load modules based on url

Time:01-11

I am trying to create an angular application, with two modules. One for the user part and one for the admin part.

I would like to load the module only if needed. For example if the requested url is /my-account it would load the user module. But if it's something that starts with /admin it should load the admin module.

After that i don't know if it's possible but each module should load his own routing (like app-routing).

For now i am just trying to change the bootstraped component based on the url.

I tried this solution: https://stackoverflow.com/a/53014303/10270107 But for me it doesn't work i have an error, and like the comment said everything is still loaded.

Here is my base application: https://stackblitz.com/edit/angular-ivy-uyub48?file=src/app/app.module.ts

CodePudding user response:

This is call LazyLoading: in the app.module you need to load the module according to route like this:

imports: [
  RouterModule.forRoot([
    {
      path: 'public',
      loadChildren: () => import('./public/public.module').then((m) => m.PublicModule),
    },
    {
      path: 'admin',
      loadChildren: () => import('./admin/admin.module').then((m) => m.AdminModule),
    },
  ]),
],

That will load the modules base on route

and inside the child modules you manage the route like this:

RouterModule.forChild([
  {
    path: 'fff',
    component: YourComponent,
  },
]),

Basically the different is that - in the parent module you need to use forRoot and in child modules you need to use forChild

CodePudding user response:

You can Create two angular libraries and build them as umd.js files Use Angular @angular/compiler to compile at run time. This works but needs research. Deprecated in V13 https://angular.io/api/core/Compiler

  •  Tags:  
  • Related