SONGSTER
SONGSTER

Reputation: 615

Multiple components per route in angular

What I want to do is, I want to load the home component and sidebar component at the same time.

const appRoutes: Routes = [
  {
    path: '', component: HomeComponent, children: [{
      path: 'sidebar', component: SidebarComponent, children: [
        { path: 'about', component: AboutComponent },
        { path: 'clients', component: ClientsComponent },
        { path: 'services', component: ServicesComponent },
        { path: 'contact', component: ContactComponent },
        { path: 'datatable', component: DataComponent }
      ]
    }]
  }

Upvotes: 10

Views: 22333

Answers (3)

Ringo
Ringo

Reputation: 621

I agree with Mike answer. If you want the sidebar component to show all the time, your home component should be the parent of sidebar. Your routing can be greatly simplify to this:

const routes: Routes = [{
  path: 'about',
  component: AboutComponent
}, {
  path: 'client',
  component: ClientComponent
}, {
  path: '**',
  redirectTo: 'about'
}]

with your app html look somewhat like this:

<div class="app">
    <header></header>
    <div class="content">
        <sidebar></sidebar>
        <router-outlet>
        </router-outlet>
    </div>
    <footer></footer>
</div>

demo:

https://stackblitz.com/edit/angular-tde6as?file=app%2Fclient%2Fclient.component.css

Upvotes: 0

Michael Kang
Michael Kang

Reputation: 52847

You can use named outlets:

const appRoutes: Routes = [
  {
    path: '', component: HomeComponent, children: [

        { path: 'about', component: AboutComponent },
        { path: 'clients', component: ClientsComponent },
        { path: 'services', component: ServicesComponent },
        { path: 'contact', component: ContactComponent },
        { path: 'datatable', component: DataComponent }
      ]
  },
  { path: '', component: SidebarComponent, outlet:'secondary' }
]

HTML:

<router-outlet></router-outlet> //primary outlet
<router-outlet name="secondary"></router-outlet>  //secondary outlet

Upvotes: 20

Mike Tung
Mike Tung

Reputation: 4821

Why not just have the HomeComponent be the parent component and SideBarComponent live inside HomeComponent's template?

Upvotes: 1

Related Questions