Tip: highlight "products" route menu when on "product/:id" page

You have routes like

{route: 'products', name: 'products', title: 'Products', 
 nav: true, moduleId: './products'},
{route: 'product/:id', name: 'product', title: 'Product', 
 moduleId: './product'},

You have built your navigation to highlight a route when it’s active.

class.bind="row.isActive ? 'active' : ''"

When user is on page “product/1”, no menu is highlighted. But you really like to highlight “products” route menu.

How to do it?

First, write down our intention into product route config settings.

{route: 'product/:id', ... , settings: {highlight: 'products'},

So instead of

row.isActive ? 'active' : ''

we want

(row.isActive || row.config.name === highlight) ? 'active' : ''

How to get current highlight? You can get from router.currentInstruction

@computedFrom('router.currentInstruction')
get highlight() {
  const inst = this.router.currentInstruction;
  return inst && inst.config.settings.highlight;
}

See a working gistrun here:

6 Likes

Hi, could i suggest you another method?

you could use just a route with an optional parameter and, if you need 2 different modules then you can use navigationStrategy:

{
   route: 'products/:id?',
   navigationStrategy: (navInstructions) => {
       if( !instruction.params.id ){
           moduleId: './products'
       }else {
           moduleId: './product'
       }
   }
}
1 Like