Do I need a routing module for every url segment?

Viewed 172

New to angular and having problems understanding how many routing modules I'll need. I'm building a multi-level side navigation. Right now I only have 1 module besides the app.module. Here's the routing info for this lazy loaded MyConfiguration module:

const routes: Routes = [
  {
    path: '',
    component: MyConfigurationComponent,
    children: [
      {
        path: 'a',
        component: AComponent
      },
      {
        path: 'b',
        component: BComponent
      },
      {
        path: 'c',
        component: CComponent,
        children: [
          {
            path: '1',
            component: OneComponent
          },
          {
            path: '2',
            component: TwoComponent
          }
        ]
      }
    ]
  }

If I want the url to update to my-configuration/c/1 when I select OneComponent does this mean that I need a new module + routing module for it?

I lazy load it from app-routing.module:

const routes: Routes = [
  { path: 'home', component: homeComponent },
  {
    path: 'my-configuration',
    loadChildren: () =>
      import('./my-configuration.module').then(
        p => p.MyConfigurationModule
      )
  },
];

I want my url to update when I select OneComponent to this:

'my-configuration/c/1'

But, it errors:

Error: Cannot match any routes. URL Segment: 'my-configuration/1'

Because the activated route is my-configuration.

Here's the handler for clicking a link:

this.router
  .navigate([this.optionSelected.code], { relativeTo: this.route })
  .then(e => {
    if (e) {
      console.log('Navigation is successful!');
    } else {
      console.log('Navigation has failed!');
    }
  });

Does this mean that I need a new module + routing module? Something like this:

const routes: Routes = [
  {
    path: 'my-configuration',
    loadChildren: () =>
      import('./my-configuration/my-configuration.module').then(
        p => p.MyConfigurationModule
      )
  },
];
1 Answers

Try this:-

Note: You need to conditionally append "../" only if you are accessing child routes of 'c'.

this.router
  .navigate(['../' + this.optionSelected.code], { relativeTo: this.route })
  .then(e => {
    if (e) {
      console.log('Navigation is successful!');
    } else {
      console.log('Navigation has failed!');
    }
  });
Related