Home > Enterprise >  How to mark a menu item as active for two different routes in Angular
How to mark a menu item as active for two different routes in Angular

Time:04-19

I am using the routerLinkActive attribute to change the background-color of my menu-items depending on the page that is currently displayed. This is the HTML for my MenuItem component:

<div  routerLinkActive="active">
  <my-icon name="{{ iconName }}"></my-icon>
  <a routerLink="{{ routerLink }}">{{ title }}</a>
</div>

When using this component, I have to pass in the routerLink attribute, such as /home. This works fine with the only issue being that I want the menu-item "Home" to be marked as active when the route is base_url/home as well as just base_url/. I don't know how to achieve this though.

In my app.module.ts file, I am defining the following routes:

RouterModule.forRoot(
  [
    {path: '', component: HomeComponent},
    {path: 'home', component: HomeComponent},
    ...
  ],

So, the HomeComponent is displayed initially, but the corresponding menu item is not marked as active.

I guess that one solution could be to simply pass in / as the routerLink for my HomeComponent and then add [routerLinkActiveOptions]="{exact:true}" to the MenuItem component. Actually, I have verified that it works. The issue that I have with this solution is, that I would really like the /home to show in my URL whenever I am displaying my HomeComponent - just for consistency, it is visible for all other pages after all.

Can someone help me out?

CodePudding user response:

The issue that I have with this solution is, that I would really like the /home to show in my URL whenever I am displaying my HomeComponent

You should use a redirect from default '' route into home route path. Then the menu will work as expected as well as your above requirement to always show the url in the form of /home

RouterModule.forRoot(
  [
    {path: '', redirectTo: '/home', pathMatch: 'full' },
    {path: 'home', component: HomeComponent},
    ...
  ],

CodePudding user response:

you need to add pathMatch

RouterModule.forRoot(
  [
    {path: '', redirectTo: 'home', pathMatch: 'full' },
    {path: 'home', component: HomeComponent},
  ],

angular routes

by default path-match strategy is prefix, Or for empty paths you can write full.

  • Related