How To Get The Current Active Route In An Aurelia ViewModel

When inside of an Aurelia ViewModel there are situations where you might want to know what the current route is within a ViewModel.

One such scenario I encountered recently where I had one View and ViewModel pair being accessed by 5 different routes. I needed to know what route was accessing my ViewModel to load different data.

This is what the second parameter of the activate method for.

activate(params, navigationInstruction) {
    console.log(navigationInstruction);
}

The navigationInstruction parameter gives you the information about the route currently accessing the ViewModel. This allows you to access everything about the route, including the navModel

This object has a tonne of information about the currently active route accessing this ViewModel:

  • moduleId – The current module path to the ViewModel (defined in app.js/app.ts)
  • name – The name of your route (defined in app.js/app.ts)
  • navModel – This pretty much gives you the same values as the other properties with exception of a couple, like isActive and relativeHref
  • route – The route pattern (defined in app.js/app.ts)
  • settings – The settings object defined in the route (defined in app.js/app.ts)
  • title – The title value for this route
  • viewPorts – An object of defined viewports for this route (defined in app.js/app.ts)

In my scenario, I needed to know the name of the route accessing the ViewModel. I knew if it was my route for numeric pagination, I could check for specific parameters. If it was the route with no parameters, I knew not to check for them and just fetch all data.

Hopefully this helps you in determining the current route in Aurelia and what is accessing your ViewModel.