角度路由routerLinkActive类即使在其他链路路由上也不会从基页中删除

问题描述 投票:2回答:3

我提供了一个很好的简单路由示例。唯一的问题是routerLinkActive正在将“baboossa”类添加到活跃的链接中。当我从家里回到“关于”或“窗口”的其他链接时,链接变为橙色(由于baboossa类),但我仍然可以看到家也是橙色。为什么现在我有2个链接添加来自routerLinkActive的类,并且类没有从家中删除?

app.component.html

<ul>
  <li><a [routerLink]="''" routerLinkActive="baboossa">Home</a></li>
  <li><a [routerLink]="'/about'" routerLinkActive="baboossa">About</a></li>
  <li><a [routerLink]="'/window'" routerLinkActive="baboossa">Window</a></li>
</ul>

<router-outlet></router-outlet>

app.module.ts

import { RouterModule } from '@angular/router';

imports: [
  RouterModule.forRoot([
    {path:'', component: HomeComponent},
    {path:'about', component: AboutComponent},
    {path:'window', component:WindowComponent}
  ])
]

styles.css的

.baboossa {background:orange;}

结果:

enter image description here enter image description here enter image description here

有人可以指出问题为什么我在其他活动链接上获得2个橙色背景而不是baseone(home)?

enter image description here

javascript angular angular-routing
3个回答
4
投票

您可以使用两种方法进行归档:

  1. 使用routerLinkActive添加routerLinkActiveOptions [routerLinkActiveOptions]="{ exact: true }"

像这样:[routerLink]="''" [routerLinkActive]="['baboossa']" [routerLinkActiveOptions]="{ exact: true }"

  1. 将空路由器path : ''重定向到路由器模块中的任何特定路径,例如“{path:'',redirectTo:'home'}。

像这样 :

[{
    path: '',    
    pathMatch : 'full',
    redirectTo: 'home'
},
{
    path: 'home',    
    component: HomeComponent
}]

并用[routerLink]="''"改变[routerLink]="'home'"

这是Stackblitz



1
投票

这是另一种方法,您可以使用命名路径作为默认路径而不是空路径。 RESTful API方法,其中URL易于理解。

<ul>
  <li><a [routerLink]="[ 'home' ]" routerLinkActive="baboossa">Home</a></li>
  <li><a [routerLink]="[ 'about' ]" routerLinkActive="baboossa">About</a></li>
  <li><a [routerLink]="'[ 'window' ]" routerLinkActive="baboossa">Window</a></li>
</ul>

<router-outlet></router-outlet>

然后

import { RouterModule } from '@angular/router';

imports: [
  RouterModule.forRoot([
    {path:'home', component: HomeComponent},
    {path:'about', component: AboutComponent},
    {path:'window', component:WindowComponent}
    {path:'**', redirectTo: 'home'}
  ])
]
© www.soinside.com 2019 - 2024. All rights reserved.