Search code examples
javascriptangularangular7angular-routingangular7-router

Using angular-router to navigate views within a page


I'm creating a web application with multiple pages, and within each page there are dynamic sections. I'd like each of these sections to use the angular router.

I've tried simply putting a named router-outlet inside the components, but it doesn't seem to work... Any thoughts?

Here's my general setup.

App template

<main>
  <router-outlet></router-outlet>
</main>

App module

const routes: Routes = [
 { 
  path: 'page', 
  component: PageModule
 }
];

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

Page template:

<tabset>
  <tab>
    <router-outlet name="section1"></router-outlet>
  </tab>
  <tab>
    <router-outlet name="section2"></router-outlet>
  </tab>
</tabset>

Page module

const routes: Routes = [
  {
    path: '',
    component: PageComponent,
  },
  {
    path: 'section1-view1',
    component: View1Component,
    outlet: 'section1',
  },
  {
    path: 'section1-view2',
    component: View2Component,
    outlet: 'section1',
  }
  // More routes ...
];

@NgModule({
  declarations: [
    PageComponent,
    View1Component,
    View2Component
  ],
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
    TabsetModule
  ]
})
export class PageModule { constructor(){} }

Solution

  • Make each component in a new module then define the internal routes in that module, so whenever you route to the module, you can route in the internal routes.

    keep your current routes as they are, and declare new module(import these modules in app.module), and within that module make new components where you want to route in that module.

    check this out: Stackblitz Just a sample example for your use.

    Here there is one component in app.module and a module called intmodule and there are two components in intmodule. From the app.module we can route between hello.component and intmodule and in intmodule we can route between comp1 and comp2.

    comment for more help :)