OdeToCode IC Logo

Dynamically Add Routes in Aurelia

Tuesday, May 31, 2016

Routes are usually defined in an Aurelia application using a model’s configureRouter method in a declarative manner.

configureRouter(config, router) {
    this.router = router; 
 
    config.title = "The App";
    config.map([
        
        { route: "", name: 'home', moduleId: "app/home", 
          title:"Home", nav:true
        },
        
        { route: "about", moduleId: "app/about", 
          title: "About", nav:true 
        }
        
    ]);
}

However, you can also add routes at anytime using the Router’s API.

constructor(router) {
    this.router = router; 
}

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

I’d stick with the declarative routing whenever possible, but dynamically adding routes is useful in a few scenarios.