Multiple components per route in angular

半城伤御伤魂 提交于 2020-01-04 11:03:32

问题


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 }
      ]
    }]
  }

回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/48244449/multiple-components-per-route-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!