Luk
Luk

Reputation: 1159

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

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 class="menu-item" 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?

Upvotes: 2

Views: 1835

Answers (2)

Bansi29
Bansi29

Reputation: 1079

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.

Upvotes: 1

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19173

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},
    ...
  ],

Upvotes: 2

Related Questions