【问题标题】:Multiple components per route in angular每条路线的多个组件角度
【发布时间】:2018-01-13 21:24:52
【问题描述】:

我想做的是,我想同时加载home componentsidebar component

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

【问题讨论】:

    标签: angular typescript angular2-routing angular4-router


    【解决方案1】:

    您可以使用命名插座:

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

    为什么不让 HomeComponent 成为父组件,而 SideBarComponent 存在于 HomeComponent 的模板中?

    【讨论】:

    • home 组件是所有其他组件代码汇集的地方。像页眉页脚等,然后家庭组件需要一个插座来加载。所以这就是为什么
    • 有一个 html 为空的组件,只需添加 router-outlet 即可解决问题
    • 我做到了。问题是 homecomponent 加载,但要加载侧边栏组件,我必须在地址栏中输入 url。我希望边栏组件和主页组件同时加载
    • @SONGSTER 从路由中移除侧边栏,使其成为 home 组件的子组件。
    • 把它从你的 Angular 路由器中移除,一切就绪。
    【解决方案3】:

    我同意迈克的回答。如果你想让侧边栏组件一直显示,你的主组件应该是侧边栏的父组件。您的路由可以大大简化为:

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

    你的应用 html 看起来有点像这样:

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

    演示:

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

    【讨论】:

    • 但是如果我希望我的主页显示侧边栏菜单中的预选选项怎么办。我该怎么做。就像我想当有人登陆主页时,他应该显示主页>关于>标记的页面
    • 或只是侧边栏>关于页面。如果他愿意,他可以选择其他选项。怎样才能完成这样的事情
    • 根据您的第一条评论,routerLinkActive 将在您的 html 中添加一个活动类。因此,它将显示您所在的路线选项处于活动状态。查看我更新的演示。
    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    相关资源
    最近更新 更多