iain
iain

Reputation: 472

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(){} }

Upvotes: 2

Views: 1861

Answers (2)

Mr-K10
Mr-K10

Reputation: 345

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 :)

Upvotes: 1

Mr.Ali
Mr.Ali

Reputation: 112

Updated

Try this one

create two separate components to be displayed on main page

ng g c section1
ng g c section2

section1 .ts file

@Component({
  selector: 'section1',
  templateUrl: './section1.component.html',
  styleUrls: ['./section1.component.css'],
})

similarly section2 .ts file

@Component({
      selector: 'section2',
      templateUrl: './section2.component.html',
      styleUrls: ['./section2.component.css'],
    })

then on the main page you can use multiple sections/components like this

page template

<div class="row">
  <div class="col-sm-5">
    <section1></section1> <!-- component selector -->
  </div>
  <div class="col-sm-5">
    <section2></section2>
  </div>
</div>

Upvotes: 0

Related Questions