Angular 2导航菜单

时间:2016-10-25 10:20:40

标签: angular angular2-routing angular2-router

我正在尝试为我的项目创建导航菜单。 我的想法是为这个菜单使用Routes数组并且它正在工作,但现在我正在尝试将url添加到我的菜单中并且它无法正常工作

enter image description here

正如您在上面的图片中看到的,我创建了带有子元素的导航菜单。 现在我想添加[routerLink]来启用链接。 对于根项目,一切正常,使用:

[routerLink]="[menuItem.route.path]"

但是对于儿童用品,它不起作用。

P.S。 路线:

    RouterModule.forRoot([
  { path: '', component: HomeComponent },
  { path: 'admin', component: HomeComponent, data: { title: "Home", icon: "home" } },
  {
    path: 'test', component: HomeComponent, data: { title: "Settings", icon: "settings" },
    children: [
      { path: '', component: HomeComponent, data: { title: "Test", icon: "power_settings_new" } },
      { path: 'settings', component: HomeComponent, data: { title: "Test2", icon: "power_settings_new" } }
    ]
  }
])

1 个答案:

答案 0 :(得分:1)

您在HomeComponent中添加了<router-outlet></router-outlet>?如果您有子路线,则必须添加<router-outlet></router-outlet>。你的问题可能是这个。

我在这里测试并以这种方式工作。我创建了4个组件(HomeComponent,Home1Component,Home2Component和Home3Component)。

在app.routing中

import {HomeComponent}            from './admin/home/home.component'
import {Home1Component}            from './admin/home1/home1.component'
import {Home2Component}            from './admin/home2/home2.component'
import {Home3Component}            from './admin/home3/home3.component'

 export const routing: ModuleWithProviders = RouterModule.forRoot([
      { path: '', component: HomeComponent },
      { path: 'admin', component: Home3Component, data: { title: "Home", icon: "home" } },
      {
        path: 'test', component: Home1Component, data: { title: "Settings", icon: "settings" },
        children: [
          { path: '', component: Home2Component, data: { title: "Test", icon: "power_settings_new" } },
          { path: 'settings', component: Home3Component, data: { title: "Test2", icon: "power_settings_new" } }
        ]
      }
    ]);
你需要放置Home1Component中的

(将加载子项):

<router-outlet></router-outlet>
app.module中的

import { AppComponent }               from './app.component';
import { HomeComponent }              from './admin/home/home.component';
import { Home1Component }             from './admin/home1/home1.component';
import { Home2Component }             from './admin/home2/home2.component';
import { Home3Component }             from './admin/home3/home3.component';

@NgModule({
  ...
  declarations: [ AppComponent, HomeComponent, Home1Component, Home2Component, Home3Component ],
  ...
})

创建路线:

<li><a routerLink="/admin">Admin</a></li>
<li><a routerLink="/test">test</a></li>
<li><a routerLink="/test/settings">teste/settings</a></li>

以这种方式测试并且有效!