0

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

Atlas91
  • 5,754
  • 17
  • 69
  • 141

1 Answers1

1

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.

GM-atteoni
  • 425
  • 4
  • 11
  • There are 2 problems in this way. Unfortunally seems that the menu doesn't keep the active state. The second one is that now in the shop component I have also the detail component when I click the button "Go to details". Both, instead of only details. I don't know if you get me – Atlas91 Jun 05 '20 at 13:36
  • Ok, for best practices with Angular, I think your 'detail' route should be a child route of 'Shop'. You can solve the second problem with a simple *ngIf trick, when you click the button the

    desapear. About the first problem, I'm trying to fix it.

    – GM-atteoni Jun 05 '20 at 13:58
  • Solved: remove the [routerLinkActiveOptions]="{exact: true}" from your shop – GM-atteoni Jun 05 '20 at 14:05
  • Yeah it's working now. Problems solved! Thank you very much. – Atlas91 Jun 05 '20 at 14:19
  • 1
    FYI i saw this information here https://angular.io/api/router/RouterLinkActive#description – GM-atteoni Jun 05 '20 at 14:21