LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Create a routeable component
  • Getting the currently active route
  • Get all registered routes
  • Creating a route
  • Creating a route with parameters
  • Creating a route with custom configuration values
  • Creating a route with a custom viewport
  • Loading data inside of a routeable component
  • Redirect away from a component

Was this helpful?

Export as PDF
  1. Getting to know Aurelia
  2. Routing
  3. @aurelia/router

Router Recipes

While the docs do a great job explaining the intricacies of the router, sometimes you just need a code snippet and a brief explanation to do something. You will find code snippets for basic things, from creating routes to working with router hooks.

Create a routeable component

A component that is loaded as part of a route definition. The IRouteableComponent

import { IRouteableComponent } from '@aurelia/router';

export class MyComponent implements IRouteableComponent {

}

Getting the currently active route

When working with the router, sometimes you want to access the currently active route. The router provides an array of activeComponents which can be one or more components currently active. In most instances, this array will only contain one component. However, if you are working with multiple viewports, this array will contain all components from those viewports.

import { IRouter, IRoute } from '@aurelia/router'; 

export class MyComponent {
    constructor(@IRouter private readonly router: IRouter) {}
    
    attached() {
        const route = this.router.activeComponents[0]?.route?.match as IRoute;
        
        if (route) {
            console.log(route.id); // Prints current route ID if a route was found
        }
    }
}

By leveraging the route.match property, we can get the currently active route. This is where you can access its data, path, name and other route configuration properties.

Get all registered routes

To get all registered routes, you can use the getRoutes method from the rootScope property of the router.

import { IRouter, IRoute } from '@aurelia/router'; 

export class MyComponent {
    constructor(@IRouter private readonly router: IRouter) {}
    
    attached() {
        const routes: IRoute[] = this.router?.rootScope?.getRoutes() ?? [];
        
        console.log(routes) // one or more registered routes
    }
}

Creating a route

export class MyApp {
    static routes = [
        {
            path: '/products',
            component: () => import('./products-page'),
            title: 'Products'
        }
    ];
}

Creating a route with parameters

A parameter is denoted by the prefixed colon : followed by the parameter's name. In this example, our parameter is called productId, which is required for the route to load.

export class MyApp {
    static routes = [
        {
            path: '/products/view/:productId',
            component: () => import('./view-product'),
            title: 'Products'
        }
    ];
}

You can have more than one parameter (as many as you like):

export class MyApp {
    static routes = [
        {
            path: '/products/view/:productId/:section',
            component: () => import('./view-product'),
            title: 'Products'
        }
    ];
}

Creating a route with custom configuration values

Routes support a custom data property allowing you to decorate your routes. Some use cases might include marking a route as requiring a user to be authenticated or an icon.

export class MyApp {
    static routes = [
        {
            path: '/products/view/:productId',
            component: () => import('./view-product'),
            title: 'Products',
            data: {
                icon: 'fa-light fa-alicorn'
            }
        }
    ];
}

Creating a route with a custom viewport

Some routes might be loaded into specific viewports in applications with multiple viewports. You can use the viewport property on routes to specify which route.

export class MyApp {
    static routes = [
        {
            path: '/products/view/:productId',
            component: () => import('./view-product'),
            title: 'Products',
            viewport: 'sidebar'
        }
    ];
}

Loading data inside of a routeable component

Inside components displayed by routes, the best place is to load data inside canLoad or load hooks. If your view depends on the data being loaded (like a product detail page), use canLoad otherwise, use load. The first argument is any parameters passed through the route.

import { IRouteableComponent } from '@aurelia/router';

export class ViewProduct implements IRouteableComponent {
    async canLoad(params) {
        this.product = this.api.loadProduct(params.productId);
    }
}

Redirect away from a component

Using the canLoad lifecycle hook, we can redirect users. In the following example, we redirect a user to a /products route. You would have this wrapped in a check to determine if the component loads or the user is redirected away.

import { IRouteableComponent } from '@aurelia/router';

export class ViewProduct implements IRouteableComponent {
    async canLoad(params) {
        return '/products';
    }
}
PreviousRouter TutorialNext@aurelia/router-lite

Last updated 1 year ago

Was this helpful?

As outlined in the section, routes can be specified using the routes decorator or the static routes property.

Creating Routes