boop
boop

Reputation: 7787

Routing to a module

Disclaimer: This is my first time programming in angular and it's quite possible that this is a misconception and therefore my question is invalid


I've started to write an app that is supposed to get several complex features. So I put a single feature in a single module so that I can just load the whole module as a simple import into my app and just have it in HTML.

Simplified folder structure

app.module.ts
app.component.ts
app.component.html
feature/feature.module.ts
feature/componentA/componentA.component.cs
...

in the FeatureModule I export my main component which contains all the sub-components.

Then in AppModule I load the other module like that

import { FeatureModule } from './feature/feature.module';

...

@NgModule({
  declarations: [ .. ],
  imports: [
    .. ,
    FeatureModule
  ],
  ...
})

Then I can add the feature component in my html. That's it.

But now I want to add routing and I need to specify a specific component, not a module.

This leads to my question: How should I route this? Or: How should I structure my complex feature to hide all the internals from the outside. I just want to expose a single "piece" that I can insert into my app. Plug and Play, if you will

Upvotes: 1

Views: 4138

Answers (2)

Sleepwalker
Sleepwalker

Reputation: 863

You can use lazy loading of routes to basically just point a route to your FeatureModule, and then let your FeatureModule have it's own route. This way everything inside your feature exept its base level module is hidden from your base router which I believe is what you want ?

For instance:

In app-routing.module.ts

...

const routes: Routes = [
  {
    path: 'feature', 
    loadChildren: () => import('./feature/feature.module.ts').then(m => m.FeatureModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Add your router module to you app.module.ts

...

@NgModule({
  imports: [
    ...,
    AppRoutingModule,
  ],
  ...
})
export class AppModule { }

Then you can add a route to your components inside FeatureModule

...
const routes: Routes = [
  {
    path: 'componenta',
    component: ComponentA
  }
];

@NgModule({
  imports: [
    ...,
    RouterModule.forChild(routes),
  ],
  ...
})
export class FeatureModule { }

Angular doc

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Look at lazy loading and the Route's loadChildren property.

Your route would look like:

const routes: Routes = [

      {
        path: 'items',
        loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
      }
    ];

And then the lazy-loaded module would have its own routing to specify what component is shown when the module is routed to. Can be just a single route, if you have only one 'feature' component in the module.

The documentation is at https://angular.io/guide/lazy-loading-ngmodules

Upvotes: 1

Related Questions