1
votes

I want to implement child routes using Aurelia Framework.

I am not looking for this solution as shown in the following link, multi-level-menu.

Below is the code:

app.html

<div class="page-host">
     <router-view></router-view>
</div>

app.js/app.ts

var _self = this;
this.router.configure(config => {
        config.map(this.routes);
        config.mapUnknownRoutes(instruction => {
        _self.router.navigate(_self.defaultRoute);
            return '';
        });

        this.router = router;
        this.sideNavObj.navigationRouteList = this.router.navigation;
        return config;
    });

page1.html

<section>
    <h2>Child Routes</h2>
    <div>
        <div class="col-md-2">
            <ul class="well nav nav-pills nav-stacked">
                <li repeat.for="row of childRoutes">
                    <span click.delegate="router.navigate('#/' + row.route)">${row.title}</span>
                </li>
            </ul>
        </div>
        <div class="col-md-10 childRouterDiv">
            <router-view></router-view>
        </div>
    </div>
</section>

page1.js/page.ts

var _self = this;
this._router.configure(config => {
        config.map(_self.childRoutes);
        return config;
    });

Scenario:

Once you navigate to page1 the respective child routes(page 1.1, page 1.2) are coming under respective page.

But if you navigate to page2 which is the part of main menu (not a child route or sub-menu), the composition/rendering is happening under the <router-view></router-view> of page1.html not app.html.

Since there are two <router-view></router-view> in my DOM, the recent one is being used.

Once I navigate to other page(s) <router-view></router-view> of app.html should be used and other(of page1.html) should be removed from the DOM.

Thanks in advance.

1

1 Answers

4
votes

As an aside, you don't need to do var _self = this; if you're using arrow functions.

When you want to have a child router, you don't have the router injected to the constructor, you write a configureRouter function on your VM. The child router will be created for you and passed to that function. This is shown in child-router in the Aurelia skeleton:

import {Router, RouterConfiguration} from 'aurelia-router'

export class ChildRouter {
  heading = 'Child Router';
  router: Router;

  configureRouter(config: RouterConfiguration, router: Router) {
    config.map([
      { route: ['', 'welcome'], name: 'welcome',       moduleId: 'welcome',       nav: true, title: 'Welcome' },
      { route: 'users',         name: 'users',         moduleId: 'users',         nav: true, title: 'Github Users' },
      { route: 'child-router',  name: 'child-router',  moduleId: 'child-router',  nav: true, title: 'Child Router' }
    ]);

    this.router = router;
  }
}