Search code examples
angulartypescriptangular2-routingmenuitem

Angular two different paths same menu item active


I have a menu like this in my app-component.ts:

<ul>
  <li>
    <a href="#" routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a>
  </li>
  <li>
    <a href="#" routerLink="/shop" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Shop</a>
  </li>

</ul>
<router-outlet></router-outlet>

with a route file like this one

export const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'shop',
    component: ChildComponent
  },
  {
    path: 'details',
    component: DetailComponent
  }
];

As you can see, I have "shop" and "details" components. Details components can be reached from the shop page by clicking a simple button. In this moment my active state on the menu selects the shop item correctly, but when I click the details button the state is no more active. Is it possibile keep the active state in the menu for both components even if I am in another route?

Here's an example

https://stackblitz.com/edit/parent-child-active-x6sp1e


Solution

  • According to Angular Documentation, your appRoutes should be like this:

    const routes: Routes = [
    { 
     path: 'shop',
     component: ChildComponent, 
      children: [
        {
          path: 'details', 
          component: DetailComponent
        }
       ] 
     }
    

    But, to reach success here, you need to have two <router-outlet></router-outlet>. One inside your Home and another inside your Shop.