要解决Angular中的routerLinkActive
没有正确工作的问题,您可以尝试以下解决方法:
确保您已正确设置了路由器:
RouterModule
并将其添加到imports
数组中。
,以便路由器可以正确显示路由组件。确认您是否正确使用routerLinkActive
指令:
routerLink
指令的链接上添加routerLinkActive
指令,并将其绑定到一个类名或一个包含类名的数组。例如:[routerLinkActive]="'active'"
或[routerLinkActive]="['active', 'highlight']"
。routerLink
指令的链接与路由配置中的路径匹配。检查样式表中的类名:
routerLinkActive
指令中的类名是否正确,并与您的样式表中的类名相匹配。确认您是否使用了正确的路由配置:
下面是一个包含代码示例的解决方法:
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.html:
app.component.css:
.active {
color: red;
}
这样,当您导航到相应的路由时,链接将获得active
类,并且文本颜色将变为红色。