首页 > 解决方案 > Angular 组件路由中的挑战

问题描述

我已经定义了一个子组件路由。

  1. 我无法从 routerLink 导航到默认路由。
  2. 父路径具有“:id”,因此对于子路由,它仅使用前缀“:id”。

路线

{
    path: ':id', component: InterviewComponent,
    children: [                          
      {
        path: '',
        component: InterviewQuestionsComponent
      },
      {
        path: ':id/interview',
        component: InterviewGridComponent
      }
    ]

  }

锚标签

<ul class="list-unstyled components">
      <li>
        <a routerLink=""><i class='interviewQuestions'></i>&nbsp; <span style="cursor: pointer;">Interview Questions</span></a>
      </li>
      <li>
        <a routerLink=":id/interview"><i class='interviews'></i>&nbsp; <span style="cursor: pointer;">Interviews</span></a>
      </li>
    </ul>

<router-outlet></router-outlet>
  1. 我无法使用 'routerLink=""' 导航到默认路由器
  2. 仅适用于“路径:':id/interview'”的路线

标签: angularangular-ui-routerangular-routing

解决方案


There are couple of things that I observed here,

  1. if I understand you correctly what you are trying to do is,

    /1 should render InterviewQuestionsComponent

    /1/interview should render InterviewGridComponent

right? correct me if I am wrong.

if this is what you want then modify your routes with below,

{
path: ':id', component: InterviewComponent,
children: [                          
  {
    path: '',
    component: InterviewQuestionsComponent
  },
  {
    path: 'interview',
    component: InterviewGridComponent
  }
]
}
  1. To navigate to each of these components, you will need 'id', which is a path param, so what you have done in routerLink is not correct.

modify it like below,

<ul class="list-unstyled components">
  <li>
    <a routerLink="1"><i class='interviewQuestions'></i>&nbsp; <span style="cursor: pointer;">Interview Questions</span></a>
  </li>
  <li>
    <a routerLink="1/interview"><i class='interviews'></i>&nbsp; <span style="cursor: pointer;">Interviews</span></a>
  </li>
</ul>

Here I have hardcoded '1' in the path, you can make it dynamic using Angular bindings. Here's a working example on stackblitz.

https://stackblitz.com/edit/angular-wipkyq


推荐阅读