如何在同一个路由器上设置多个 URL link

How to multiple URLs on same router link

我正在 angular 中进行一个小测试项目,我想使用 angular 路由器插座包括一个侧面导航。我希望有两个 links:

<a class="nav-link text-white" [routerLink]='["/link/to/one"]' routerLinkActive="aLink" [routerLinkActiveOptions]="{ exact: true }">Component 1</a>
<a class="nav-link text-white" [routerLink]='["/another/link/to/component"]' routerLinkActive="aLink" [routerLinkActiveOptions]="{ exact: true }">Component 2</a>

可以从其中一个组件导航到几个子页面。但他们不需要显示为路由器 link.

所以我网站的结构可以是例如:

|-Comopnent 1
|
|-Component 2
   |- Component 3 
   |- Component 4 

所以我希望用户能够通过路由器 links 导航到 Component2。从这个组件,用户可以通过代码重定向到组件 3 和 4。但我不希望他们有额外的路由器 links,我希望导航菜单中仍然突出显示组件 2。

在我的 app.module.ts 中,我基本上声明了路线:

RouterModule.forRoot([
  { path: '', component: HomeComponent, pathMatch: 'full'},
  { path: '/link/to/one', component: Component1 },
  { path: '/another/link/to/component', component: Component2 },
])

如何从Component2调用Component3&4,让路由在导航栏中高亮显示Component2?

此致

您只需将 Component3Component4 设置为在子路由上显示即可。

因此您的路由器配置将类似于:

[
  { path: 'one', component: OneComponent },
  { path: 'two', component: TwoComponent, children: [
      { path: 'three', component: ThreeComponent },
      { path: 'four', component: FourComponent },
    ] 
  },
]

然后 routerLinkActive 会处理剩下的事情。

active CSS Class 中,我将 color 设置为 red。因此,无论哪个 link 处于活动状态,它都会变成红色。

您也可以通过在地址栏中手动输入 /two/three/two/four 来测试它。


Here's a Working Sample StackBlitz for your ref.

TL;博士

将您的 Component 3Component 4 路由配置为 Component2 的子路由,然后从链接到 [=16= 的 routerlink 中删除您的 [routerLinkActiveOptions]="{ exact: true }" ].

描述

我想你已经知道答案了,关键是routerLinkActiveOptions

首先,像这样配置你的路由:

RouterModule.forRoot([
  { path: '', component: HomeComponent, pathMatch: 'full'},
  { path: '/link/to/one', component: Component1 },
  { path: '/another/link/to/component', component: Component2, children: [
      { path: '/component3', component: Component3 },
      { path: '/component4', component: Component4 },
    ],
  },
])

然后,改变你的routerLinkActiveOptions

之前:

<a class="nav-link text-white" [routerLink]='["/another/link/to/component"]' routerLinkActive="aLink" [routerLinkActiveOptions]="{ exact: true }">Component 2</a

之后:

<a class="nav-link text-white" [routerLink]='["/another/link/to/component"]' routerLinkActive="aLink" [routerLinkActiveOptions]="{ exact: false }">Component 2</a

区别是[routerLinkActiveOptions]="{ exact: false }".

但是,routerLinkActiveOptions.exact的默认值是false,所以和去掉routerLinkActiveOptions一样。

<a class="nav-link text-white" [routerLink]='["/another/link/to/component"]' routerLinkActive="aLink">Component 2</a