How to access routes in a layout file

Hello guys!

I have an application in which for some of my routes I have used a different layout where I want to have access to the list of routes and the current active route. I have use dependency injection to pass the Router instance to the class of my layout, however that instance has no routes in its navigation property. Did I miss anything or should I use another workaround?

Here’s my app component in which I set up the main routes:

import { RouterConfiguration, Router } from 'aurelia-router';
export class App {
  private router: Router;

  configureRouter(config: RouterConfiguration, router: Router): void {

    this.router = router;

    config.title = 'Contact Manager';
    config.options.pushState = false;
    config.options.root = '/';

    config.mapUnknownRoutes('./welcome/not-found.html');

    config.map([
      { route: '', redirect: 'welcome' },
      {
        route: 'welcome',
        name: 'welcome',
        moduleId: './welcome/welcome',
        nav: 1, title: 'Home',
        // layoutView: './layouts/default.html',
        layoutViewModel: './layouts/default'
      },
      {
        route: 'contacts',
        name: 'contacts',
        moduleId: './contacts/contact-route',
        nav: 2,
        // layoutView: './layouts/default.html',
        layoutViewModel: './layouts/default'
      },
      {
        route: 'login',
        name: 'login',
        moduleId: './login/login-component',
        nav: 3, title: 'Login'
      }
    ]);
  }
}

The followings are my layout.html and its corresponding class ( ts file ):

<template>
  <nav>
      <ul repeat.for="nav of router.navigation">
          <li class="${nav.isActive ? 'active' : ''}">
            <a href.bind="nav.href">
              ${nav.title}
            </a>
          </li>
      </ul>
  </nav>
</template>
import { Router } from "aurelia-router";
import { autoinject } from "aurelia-framework";

@autoinject()
export class DefaultLayout {
  constructor(private router: Router) { }
}

What I expect is that at least I have the list of routes when I navigate to any route which uses this layout.

2 Likes

Dear @jwx, can you help on this thread?

1 Like

I couldn’t reproduce the issue you are having. Can you have a look at this sandbox https://codesandbox.io/s/5y6vw9zjm4 and help repro it?

2 Likes

@bigopon

Thanks for the great sandbox you have created, the code just works fine in the sandbox, I get the router with all the routes defined in the current scope, so I have to dig into my repository to figure out what’s wrong with my code.

Thanks

1 Like