J4v4Scr1pt
J4v4Scr1pt

Reputation: 303

Adding or not adding route in Aurelia

I am trying to add a route deppending on a boolean, so if the condtion is meet the route will show and be in the navbar and if not it will not be added.

I have trided to change nav: option depending on a condtion, but I have missed something...

{ 
  route: 'aRoute', 
  moduleId: 'modules/something/mySite, 
  nav: cond ? true : false, 
  title: 'mySite', 
  isStatic: false
}

Probably I am stupid but I need help on this.. :/

Upvotes: 0

Views: 171

Answers (2)

Gaet
Gaet

Reputation: 689

The following post should help you do what you want: http://odetocode.com/blogs/scott/archive/2016/05/31/dynamically-add-routes-in-aurelia.aspx

It shows how to add a route dynamically by doing this:

this.router.addRoute(
         { route: "secret", name: 'secret', moduleId: "app/secret", 
           title:"Secret", nav:true
         }
    );

then refreshing the router with this method call (which you are apparently missing):

this.router.refreshNavigation();

Upvotes: 1

Miroslav Popovic
Miroslav Popovic

Reputation: 12128

I'm not 100% sure, but routes are probably built one time and reused, at least those that are part of navigation model (nav === true). That would mean that you cannot use dynamic expression for nav as it would be processed only once.

If you only need this for the purpose of displaying the route in navbar, then you can create a workaround using settings property to mark the route somehow and do condition check when creating navbar.

{ 
  route: 'aRoute', 
  moduleId: 'modules/something/mySite, 
  nav: true, 
  title: 'mySite', 
  settings: { occasionallyVisible: true } // add your own properties here...
}

I used settings.occasionallyVisible property, but you can add whatever you like.

<li repeat.for="route of router.navigation" 
    if.bind="!route.settings || !route.settings.occasionallyVisible || cond">
  <a href.bind="route.href">${route.title}</a>
</li>

Navigation route will be displayed if it doesn't have settings property OR settings.occasionallyVisible is falsy OR cond is true. Of course, cond would be that condition you need.

Not as elegant, but it should get the work done until you get the better answer :)

Upvotes: 2

Related Questions