如何在angular4中导航到子路由?

时间:2018-03-19 09:27:03

标签: angular

我已设置路由,如下所示:

export const Approute: Routes = [
  {
    path: '',
    component: DashboardComponent
  },
  {
    path: 'add-course',
    component: AddCourseComponent
  },
  {
    path: 'builder',
    component: BuilderComponent,
    children: [
      { path: 'add-builder', component: AddBuilderComponent},
      { path: 'list-builder', component: ListBuilderComponent}
    ]
  }
];

我的HTML如下

<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
      <li class="active">
          <a routerLink="/"><i class="fa fa-fw fa-dashboard"></i> Dashboard</a>
      </li>
      <li>
          <a routerLink="add-course"><i class="fa fa-home"></i> Add/view Villa</a>
      </li>
      <li>
          <a (click)="toggleDashboard()" routerLink="builder"><i class="fa fa-fw fa-arrows-v"></i> Builder Management <i class="fa fa-fw fa-caret-down"></i></a>

          <ul id="demo" class="collapse" *ngIf="showDropdown === true" style="display: inline-block;">
              <li>
                  <a routerLink="add-builder">Add Builder</a>
              </li>
              <li>
                  <a routerLink="list-builder">List Builder</a>
              </li>
          </ul>
      </li>
  </ul>
</div>

当我尝试导航到DashboardComponentAddCourseComponent我能够执行此操作时,但当我将鼠标悬停在builder的子链接上时 http://localhost:4200/add-builder而应显示并导航至http://localhost:4200/builder/add-builder

如果我手动导航到http://localhost:4200/builder/add-builder,但不能从视图中导航。

哪里出错?

2 个答案:

答案 0 :(得分:1)

路由与您当前的路由器状态有关。

如果您处于第一级路由中,那么

routerLink="add-course" --> domain.com/add-course
routerLink="add-builder" --> domain.com/add-builder

如果要直接路由到子路由,则必须使用此

routerLink="builder/add-builder"
[routerLink]="['builder', 'add-builder']"

答案 1 :(得分:1)

更改模板如下

<li>
  <a [routerLink]="['/builder/add-builder']">Add Builder</a>
</li>
<li>
  <a [routerLink]="['/builder/list-builder']">List Builder</a>
</li>

供参考visit