Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
New to Javascript, Node.js and front-end development in general? Don't worry, we got you.
Welcome to the magical world of Javascript development. This guide is for any newcomer to front-end development who isn't that experienced with modern tooling or Javascript frameworks.
For the purposes of this tutorial and as a general rule for any modern framework like Aurelia, you will be using a terminal of some sort. On Windows, this can be the Command Prompt or Powershell. On macOS, it'll be Terminal (or any other Terminal alternative), the same thing with Linux.
To work with Aurelia, you will need to install Node.js. If you are new to Node.js, it is used by almost every tool in the front-end ecosystem now, from Webpack to other niche bundlers and tools. It underpins the front-end ecosystem.
The easiest way to install Node.js is from the official website here. Download the installer for your operating system and then follow the prompts.
To write code, you need an editor that will help you. The most popular choice for Javascript development is Visual Studio Code. It is a completely free and open-source code editor made by Microsoft, which has great support for Aurelia applications and Node.js.
We will be following the instructions in the Quick install guide to bootstrap a new Aurelia application. After installing Node.js, that's it. You don't need to install anything else to create a new Aurelia application, here's how we do it.
Open up a Terminal/Command Prompt window and run the following:
npx makes aureliaYou are going to be presented with a few options when you run this command. Don't worry, we'll go through each screen step by step.
You will be asked to enter a name for your project, this can be anything you want. If you can't think of a name just enter my-app and then hit enter.
In step 2 you will be presented with three options.
Option one: "Default ESNext Aurelia 2 App" this is a basic Aurelia 2 Javascript application using Babel for transpiling and Webpack for the bundler.
Option two: "Default Typescript Aurelia 2 App" this is a basic Aurelia 2 TypeScript application with Webpack for the bundler.
Option three: "Custom Aurelia 2 App" no defaults, you choose everything.
In this guide, we are going to go with the most straightforward option, option #1.
You are going to be asked if you want to install the Npm dependencies and the answer is yes. For this guide we are using Npm, so select option #2.
Depending on your internet connection speed, this can take a while.
After the installation is finished you should see a little block of text with the heading, "Get Started" follow the instructions. Firstly, cd my-app to go into the directory where we installed our app. Then run npm start to run our example app.
Your web browser should open automatically and point to http://localhost:9000
Any changes you make to the files in the src directory of your app will cause the dev server to refresh the page with your new changes. Edit my-app.html and save it to see the browser update. Cool!
In the last section we created a new application and ran the development server, but in the "real world" you will build and deploy your site for production.
Run the Npm build command by running the following in your Terminal or Command Prompt window:
npm run buildThis will build your application for production and create a new folder called dist.
Understand what areas of the framework to learn next, and how to proceed from here on out.
In our hello world example we touched upon some very basic and light Aurelia concepts. The most important of those is the view/view-model relationship. However, please note that you can write Aurelia applications in a wide variety of different ways, including custom elements without view models.
It is highly recommended that you have a read through additional sections in the "Getting Started" section to become familiar with the templating syntax, building components with bindable properties, looping through collections and more.
Once you are familiar with Aurelia's templating syntax and conventions, you will discover that you end up applying these templating basics to every app that you build.
If you followed along with our tutorial, you would now have a functional hello world application. The application will function like the one below. Typing into the text input field should dynamically display the value you entered.
Learn to use Aurelia's project scaffold tooling to create your first project setup.
There are various ways that you can set up an Aurelia project, including everything from adding a simple script tag to your HTML page to creating a custom configuration. One of the easiest and most powerful ways to get started is by using
Before you run makes, you will need a recent version of Node.js installed on your machine. If you do not have Node.js, you can Please ensure that Node.js is up-to-date if you already have it installed.
Next, using , a tool distributed with Node.js, we'll create a new Aurelia app. Open a command prompt and run the following command:
makes will then start the Aurelia project wizard, asking you a few questions to help you get things set up properly. When prompted, give your project the name "hello-world" and then select a default setup, either ESNext (Javascript) or TypeScript, depending on your preference. Finally, choose "yes" to install the project dependencies.
You have now created a hello world app without writing a single line code, well done. However, we'll be updating our app to allow for text input so we can make it say, "Hello" to whoever we want in the next section.
You now have an Aurelia setup ready for you to run, debug, or deploy. To ensure that everything is working properly, cd into your project folder and run npm start. Your project will then build and a web browser will open, displaying the message "Hello World".
Congratulations! 🎊 You just ran your first Aurelia app. Now, let's get building.
Before you can build an application with Aurelia, you need to meet a couple of prerequisites.
Aurelia was designed to make building web applications and rich UI's easy. Living by the mantra of; Simple, Powerful and Unobtrusive, you have everything you need right out of the box to start building feature-rich web applications.
This section aims to give you a brief technical overview of how Aurelia works, but it is not intended to be a tutorial or reference. If you are looking for a nice gentle introduction to Aurelia that will only take a few minutes of your time the is a great place to start.
The core concepts of Aurelia are simple; HTML, CSS and Javascript. While Aurelia does introduce its own templating language you will need to become familiar with, it is enhanced HTML, so the syntax and concepts will feel familiar to you already.
Underpinning Aurelia is the view-model and view convention. Out-of-the-box, Aurelia assumes that your components are made up of both a view model (.js or .ts file) as well as an accompanying view with a .html file extension.
If you have worked with .NET or other frameworks that use similar concepts, the view-model and view paradigm will be familiar with you. The view-model contains the business logic and data, the view is responsible for displaying it.
Like all concepts in Aurelia, these are default conventions and can be changed as needed.
Much like other fully-featured Javascript frameworks and once again, .NET, Aurelia features a robust dependency injection system that allows you to manage your in-app dependencies. You will learn about the benefits of dependency injection in other parts of the documentation, but it plays a fundamental part in Aurelia.
To create new Aurelia applications using the Aurelia CLI via Makes, you will need to ensure you have Node.js installed. The latest version of Node is always recommended and preferable. While Node can be installed through different methods, the easiest is to obtain a distributable from the .
Aurelia does not require you to install any global Node packages, instead of using the scaffolding tool, new Aurelia applications can be generated by running the following command.
You will then be presented with the Aurelia CLI screen which will first ask for a project name, then guide you through some options. The fastest way to get started is by choosing either the ESNext or TypeScript default options (1 and 2).
We highly recommend choosing TypeScript for any new Aurelia applications. With TypeScript you get the benefits of intellisense and type safety.
Once the CLI process is finished and you have installed the dependencies for your new app, run npm start in the project directory, a browser window will open up with the new Aurelia application you just generated running.
Take a look at our beginner-friendly obligatory hello world introduction to Aurelia . And if you want to dive even deeper (perhaps you've dabbled in Aurelia before) we have a fantastic selection of tutorials .
A view-model is where your business logic will live for your components. Follow along as you create your first view-model.
Aurelia as a default convention works on the premise of a view and view-model, both of which are tied together. The view-model is where your business logic lives and, if you have ever worked with .NET before (or other frameworks), you might refer to this as the controller.
Navigate to the src directory where your application code lives and open up the my-app(.ts/.js file. This is the main entry point for the application and this file is where business logic would live. As you can see, there is not a lot going on at the moment.
The class property message contains a string and within our view, we are displaying it using interpolation.
We are now going to create a new component which will be a smarter hello component. Inside of src create a new file called hello-name and use the appropriate file extension depending on whether you are using TypeScript or not. So, hello-name.ts or hello-name.js.
Notice how our new component doesn't look much different than the generated one? That's intentional. We are going to bind to this name property using two-way binding from within our view. We don't need any callback functions to update this value either.
Nice one! You just created a custom element view-model. It might not look like much, but you just learned a very core fundamental concept of building Aurelia applications. A view-model can be as simple and complex as you want it to be.
In the next chapter, we will hook this up with our view and allow a text input to change this value.
export class MyApp {
message = 'Hello World!';
}<div class="message">${message}</div>export class HelloName {
name = 'Person';
}npx makes aurelianpx makes aureliaGet acquainted with Aurelia, the documentation, and how to get started.
Welcome to Aurelia, the future-oriented, open-source JavaScript platform for crafting extraordinary web, mobile, and desktop applications. At its core, Aurelia is more than just a framework; it believes in the unbridled power of open web standards. With Aurelia, your development experience is streamlined, intuitive, and remarkably flexible.
Aurelia isn't just feature-rich; it's a testament to high performance and extensive extensibility, offering a component-oriented design that's fully testable. It's built for developers who know the value of simplicity and the importance of conventions that don't obstruct but enhance creativity. 😎
To start, jump to our Quick Start Guide or read on for an overview.
Aurelia emerges as a beacon of innovation and power in front-end development in a sea of frameworks. Here's why Aurelia might be the perfect choice for your next project:
All-in-One Ecosystem: Aurelia is your Swiss Army knife, offering everything from dependency injection to routing, eliminating the need to juggle multiple libraries. Its ecosystem extends to plugins for internationalization, validation, and more, supported by tools like a CLI and a VS Code plugin for seamless development. And with Aurelia, flexibility is key; you can customize every aspect, including the templating/binding engine.
Unparalleled Performance: Speed and efficiency are in Aurelia's DNA. It consistently outperforms competitors in benchmarks thanks to its sophisticated batched rendering and efficient memory usage.
Data-Binding Done Right: Aurelia harmonizes the safety of uni-directional data flow with data-binding productivity, ensuring both performance and ease of development.
Stability in a Dynamic World: Since our 1.0 release in 2016, Aurelia has maintained API stability, innovating without breaking changes, a testament to our commitment to developer trust.
Adherence to High Standards: Aurelia is a paragon of standards compliance, focusing on modern JavaScript and Web Components without unnecessary abstractions.
Empowering Developers: Aurelia's philosophy is simple: empower developers with plain JavaScript/TypeScript and get out of the way. This results in cleaner, more maintainable code.
Ease of Learning and Use: Aurelia's design is intuitive and consistent, minimizing the learning curve and maximizing productivity with solid, simple conventions.
Seamless Integration: Aurelia plays well with others. Its adherence to web standards makes it a breeze to integrate with any third-party library or framework.
A Vibrant Open-Source Community: Embrace the open-source ethos with Aurelia, licensed under MIT, without restrictive clauses. Join a community that thrives on collaboration and innovation.
A Welcoming and Supportive Community: Our active core team and Discord server embody a culture of welcome and support, where every developer is a valued member of the Aurelia family.
While it's true that Aurelia's ecosystem and community might seem modest compared to some of its more populous counterparts, this perceived underdog status is, in fact, one of its greatest strengths. Aurelia represents a boutique choice in web frameworks, prioritizing quality over quantity and fostering a tight-knit, highly engaged community. This approach translates to a more focused, consistent, and dedicated development experience, both in terms of the framework itself and the support you receive from the community.
Direct Impact: In a smaller community, each member's voice and contribution have a more significant impact. Developers have direct access to the core team, fostering a collaborative environment where feedback and contributions influence the framework's evolution.
Quality Over Quantity: Aurelia focuses on delivering a high-quality, refined development experience. This means that each plugin, library, and tool in the ecosystem has been carefully crafted and thoroughly vetted to meet high standards.
Nurturing Innovation: A smaller ecosystem doesn't mean limited capabilities. On the contrary, it often leads to innovative solutions and creative problem-solving, as developers are encouraged to think outside the box.
Stronger Connections: A smaller community fosters closer relationships, leading to more meaningful interactions, collaborations, and a sense of belonging. This environment is conducive to a supportive and helpful atmosphere where developers at all levels can thrive.
The size of a community or ecosystem should not be the sole criterion for its effectiveness. In many cases, the quality of interactions, the dedication of its members, and the framework's alignment with your project's needs are far more critical factors. Aurelia's commitment to standards, modern best practices, and empowering approach offers a unique and rewarding development experience that stands on its own merits. Aurelia isn't trying to reinvent the wheel or make your life a misery by changing its API with every major release.
In a landscape where Virtual DOM is often touted as a necessity, Aurelia confidently takes a different path. Aurelia's choice not to use a Virtual DOM is a deliberate and strategic decision grounded in a philosophy that prioritizes efficiency, simplicity, and alignment with web standards.
Directness and Efficiency: Aurelia interacts directly and efficiently with the DOM. By avoiding the overhead of a Virtual DOM, Aurelia ensures faster rendering and updates, leading to a smoother user experience.
Simplicity and Predictability: Without the abstraction layer of a Virtual DOM, Aurelia offers a more straightforward and predictable development experience. Developers work closer to the web platform, leveraging native browser capabilities for DOM manipulation.
Optimal Performance: Aurelia's approach to DOM updates is highly optimized. It intelligently manages DOM changes, ensuring minimal performance overhead. This results in applications that are not only fast but also more resource-efficient. Let's say Aurelia isn't going to drain your phone or Macbook Pro battery.
Aligned with Web Standards: Aurelia's commitment to standards means that it leverages the native capabilities of modern browsers, ensuring compatibility and future-proofing your applications. If the browser can do it, Aurelia won't try one-upping it by rolling its own implementation.
Less Complexity, More Control: By avoiding a Virtual DOM, Aurelia reduces the complexity of your application's architecture. This direct approach gives developers more control and understanding of how their application interacts with the browser.
Tailored for Modern Web Development: Aurelia is designed to meet the needs of modern web applications. Its efficient, standards-based approach is perfectly suited for today's dynamic, interactive web experiences.
The decision to not use a Virtual DOM is a reflection of Aurelia's overarching philosophy: to provide a powerful, efficient, and straightforward framework that stays true to the nature of the web. This approach encourages developers to build applications that are both performant and maintainable, leveraging the full potential of the web platform.
Your journey with Aurelia begins here in our meticulously crafted documentation. Start with the Quick Start Guide to grasp the basics of building an Aurelia application. The "Getting Started" section is your next stop, followed by "App Basics" for a deep dive into regular Aurelia usage.
As your comfort with Aurelia grows, explore "Advanced Scenarios" for insights into performance optimization and large-scale project management. While you may find less need for raw API documentation due to Aurelia's convention-based approach, our "API" section is comprehensive. Don't miss the "Examples" section, where practical code samples for common scenarios are found. And, our "Resources" section is a treasure trove of FAQs, framework comparisons, and much more.
Did you find something amiss in our documentation? Every page includes an "Edit on GitHub" link, making it easy to contribute corrections or improvements.
As you become more and more familiar with Aurelia, perhaps you will even come up with something that you would like to share with the community. 🎉 The Aurelia team welcomes any contributions you feel would benefit others in the community. Check out the "Community Contribution" section if that is the case. We also welcome any feedback or suggestions that will help improve Aurelia and enrich the community. Check out the "Contributor Guide" for details about the contributing process and how to contact us.
You're in the right place. If you are starting with Aurelia, we highly recommend reading through our Quick Start Guide. It will show you how to create a project and build your first components using Aurelia's powerful templating system.
A developer guide for enabling SVG binding in the Aurelia.
Learn about enabling SVG binding in Aurelia template.
By default, Aurelia won't work with SVG elements, since SVG elements and their attributes require different parsing rules. To teach Aurelia how to handle SVG element bindings, add the SVGAnalyzer like the following example:
import { SVGAnalyzer } from '@aurelia/runtime-html';
import { Aurelia } from 'aurelia';
Aurelia
.register(SVGAnalyzer) // <-- add this line
...After adding this registration, bindings with attributes will work as expected and the syntax is the same with the other bindings. Readmore on the basic binding syntax of Aurelia here.
In your view templates, you can specify inline variables using the <let> custom element.
The <let> element supports working with interpolation strings, plain strings, referencing view model variables, and other let bindings within your templates.
<let some-var="This is a string value"></let>You could then display this value using its camelCase variant:
<p>${someVar}</p>You can bind to variable values in a <let> too:
<let math-equation.bind="1 + 2 + 5"></let>
<!-- This will display 8 -->
<p>${mathEquation}</p>The router emits several events via the Event Aggregator, allowing you to listen to router events. In some situations, you might opt for a router hook, but in other cases, an event might be what you are after.
A good example of where using events might be more appropriate is showing and hiding loaders and other parts of your applications related to routing.
The events fired are:
au:router:router-start
au:router:router-stop
au:router:navigation-start
au:router:navigation-end
au:router:navigation-cancel
au:router:navigation-error
To listen to these events, you subscribe to them using the event aggregator like this:
import { IEventAggregator } from 'aurelia';
import { IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
bound() {
this.ea.subscribe('au:router:navigation-start', payload => {
// Do stuff inside of this callback
});
}
} As you might expect, these events are named in an intuitive way depending on the action taking place inside the router.
Attempted to jitRegister an intrinsic type: yyyy. Did you forget to add @inject(Key)
Attempted to jitRegister an intrinsic type: yyyy. Did you forget to add @inject(Key)
Interface name
A DI container is trying to resolve an instance of an interface, but there is no registration for it. This means the instance you are trying to load has not been registered with Dependency Injection.
Ensure that you are registering your interface with Aurelia. This can be done inside of the register method on the Aurelia instance or through the DI methods themselves.
Please also note that this error could be caused by a plugin and not your application. After ruling out that the error is not being caused by your code, try removing any registered plugins one at a time to see if the error resolves itself.
yyyy not registered, did you forget to add @singleton()?
yyyy not registered, did you forget to add @singleton()?
Name of the key being resolved
A DI container is trying to resolve a key, but there's not a known strategy for it.
Try adding a strategy for your resolved key. You can do this using @singleton or other forms of DI resolution
Please also note that this error could be caused by a plugin and not your application. After ruling out that the error is not being caused by your code, try removing any registered plugins one at a time to see if the error resolves itself.
Aurelia 2’s templating system offers a powerful and intuitive way to build and manage the user interface of your web application. It goes beyond the traditional boundaries of HTML, infusing it with enhanced capabilities to create dynamic and interactive user experiences. At the heart of Aurelia 2's templating is the seamless connection between your HTML templates and the underlying JavaScript or TypeScript code, enabling a responsive and data-driven UI.
In Aurelia 2, templates are not just static HTML files. They are dynamic views that interact with the underlying logic of your application, responding to user actions and data changes. This integration makes your development process more efficient, allowing you to build complex UIs with less code and greater clarity.
From the moment you scaffold a new Aurelia 2 project, you engage with templates that are both familiar in their HTML structure and powerful in their extended functionality. Whether defining the layout for a new component or displaying data in your HTML, Aurelia 2's templating syntax is designed to be both developer-friendly and highly expressive.
Two-Way Data Binding: Aurelia's robust data binding system ensures a seamless data flow between your application’s model and the view, keeping both in sync without extra effort.
Custom Elements and Attributes: Extend your HTML with custom elements and attributes that encapsulate complex behaviors, promoting code reuse and modularity.
Adaptive Dynamic Composition: Dynamically render components and templates based on your application's state or user interactions, enabling the creation of flexible and adaptive UIs.
Rich Templating Syntax: Utilize Aurelia's powerful templating syntax for iterating over data, conditionally rendering parts of your UI, and easily handling events.
Expression and Interpolation: Effortlessly bind data to your templates and manipulate attributes with Aurelia’s straightforward expression syntax.
Learn the basics of Aurelia by building an interactive Hello, World! application
This guide will take you through creating a hello world app using Aurelia and briefly explain its main concepts. We will be building a simple hello, world example with a text field you can enter a name into and watch the view update. We assume you are familiar with JavaScript, HTML, and CSS.
Here's what you'll learn...
How to set up a new Aurelia project.
Creating components from view-models and views.
The basics of templating and binding.
Where to go from here.
When you complete this guide, you'll be ready to take your first steps building your own Aurelia app and, you'll have the resources you need to continue into more advanced topics. So, what are you waiting for? Let's get started!
Text interpolation allows you to display values within your template views. By leveraging ${}, a dollar sign followed by opening and closing curly braces, you can display values inside your views. The syntax will be familiar to you if you are familiar with .
Interpolation can be used to display the value of variables within your HTML templates, object properties and other forms of valid data.
To show how interpolation works, here is an example.
Notice how the variable we reference in our HTML template is the same as it is defined inside of our view model? Anything specified on our view model class is accessible in the view. Aurelia will replace ${myName} with Aurelia think of it as a fancy string replacement. All properties defined in your view model will be accessible inside your templates.
A template expression allows you to perform code operations inside of ${} we learned about earlier. You can perform addition, subtraction and even call functions inside of interpolation.
In the following simple example, we are adding two and two together. The value that will be displayed will be 4.
You can call functions with parameters if you have a function inside your view model.
You can also use ternaries inside of your interpolation expressions:
Also supported in template expressions is optional syntax. Aurelia supports the following optional syntax in templates.
??
?.
?.()
?.[]
While Aurelia supports a few optional syntaxes, ??= is not supported.
Using optional syntax and nullish coalescing allows us to create safer expressions without the need for if.bind or boilerplate code in view models.
This can help clean up what otherwise might have been long and complex ternary expressions to achieve the above result.
You would be forgiven for thinking that you can do pretty much anything that Javascript allows you to do, but there are limitations in what you can do inside of interpolation you need to be aware of.
Expressions cannot be chained using ; or ,
You cannot use primitives such as Boolean, String, instanceOf, typeof and so on
You can only use the pipe separator | when using value converters but not as a bitwise operator
An element in two places at once.
There are situations that some elements of a custom element should be rendered at a different location within the document, usually at the bottom of a document body or even inside of another element entirely. Aurelia supports this intuitively with the portal custom attribute.
While the location of the rendered element changes, it retains its current binding context. A great use for the portal attribute is when you want to ensure an element is displayed in the proper stacking order without needing to use CSS hacks like z-index:9999
Using the portal attribute without any configuration options will portal the element to beneath the document body (before the closing body tag).
If you want to choose where a portalled element is moved to, you can supply a CSS selector where it should be moved.
Target an element with an ID of somewhere:
Target an element by class:
Target an element by tagName:
The portal attribute can also reference other elements with a ref attribute on them.
You can also target elements not using the ref attribute too. A good example is a custom element. Maybe you want to portal a section of a child element to the parent element.
We can do things with the injected element instance, like access the parentElement or other non-standard scenarios you might encounter.
You could also do this with query calls such as querySelector and so forth as well aliased to class properties.
By default, the portal attribute will portal your elements before the closing tag of your target. By default using portal without any configuration values will portal it just before the closing </body> tag.
We can override this behavior using the position property and the following values:
beforebegin
afterbegin
beforeend (the default value)
afterend
In this example, our element will move to just after the opening body tag <body> the other values are self-explanatory.
Use a declarative approach to describe how your component should be rendered.
In the previous section, we created a basic view model, and you are probably sceptical that we are now going to create a view with a text input that updates this value without writing any more Javascript.
Inside the src directory create a new file called hello-name.html this will complicate the view model you already have (hello-name.ts or hello-name.js).
Firstly, let's write the code to display the value. Notice how we are using interpolation to print the value like the default generated my-app.html file was? ${name} the value inside the curly braces references the class property we defined in the previous section, by the name of name.
I would say run the app and see it in action, but we haven't imported our custom element just yet. Let's do that now.
Inside of my-app.html replace the entire file with the following:
We use the import element to include our newly created component. Take note there is a lack of file extension. This is because Aurelia will know to include our view-model and, in turn, include our view and any styles.
We then reference our custom element by its name. Aurelia knows using default conventions to take the file name, strip the file extension and use that as the tag name (this is configurable but beyond the scope of this tutorial).
If you were to run the app using npm start you would then see your application rendering your new component. You should see the text, Hello, Person! rendering in the view. Once you have the app running, leave it running as any changes you make will automatically be detected and re-rendered.
We have a functional custom element, but we promised we would be able to update the name with any value we want. Inside of hello-name.html add the following beneath the existing heading.
You should now see a text input with the value Person inside of it. By adding value.bind to the input, Aurelia will use two-way binding by default. This means it will show the value from the view-model inside of the view, and if it changes in either view or view-model, it will be updated. Think of a two-way binding as syncing the value.
Type something into the text input and you should see the heading value change as you type. This works because Aurelia binds to the native value property of the text input and keeps track of the changes for you without needing to use callbacks or anything else.
As you might have noticed, there really is not that much code here. Leveraging Aurelia's conventions and defaults allows you to write Aurelia applications without the verbosity and without writing tens of lines of code to do things like binding or printing values.
<div portal>My markup moves to beneath the body by default</div><div portal="#somewhere">My markup moves toto DIV with ID somewhere</div>
<div id="somewhere"><!-- The element will be portalled here --></div><div portal=".somewhere">My markup moves to DIV with class somewhere</div>
<div class="somewhere"><!-- The element will be portalled here --></div><div portal="body">My markup moves to beneath the body (just before the closing tag)</div><div portal="target.bind: somewhereElement">My markup moves to beneath the body</div>
<div ref="somewhereElement"><!-- The element will be portalled here --></div>import { INode } from 'aurelia';
export class MyComponent {
constructor(@INode readonly element: HTMLElement) {}
}<div>
<div class="header" portal="target.bind: element.parentElement"></div>
</div><div portal="target: body; position: afterbegin;">My markup moves to beneath the body by default</div><div>
<h4>Hello, ${name}!</h4>
</div><import from="./hello-name"></import>
<hello-name></hello-name><div>
<h4>Hello, ${name}!</h4>
<p><input type="text" value.bind="name"></p>
</div>export class MyApp {
myName = 'Aurelia';
}<p>Hello, my name is ${myName}</p><p>Quick maths: ${2 + 2}</p>export class MyApp {
adder(val1, val2) {
return parseInt(val1) + parseInt(val2);
}
}<p>Behold mathematics, 6 + 1 = ${adder(6, 1)}</p><p>${isTrue ? 'True' : 'False'}</p>${myValue ?? 'Some default'}Attribute binding in Aurelia is a powerful feature that allows you to bind to any native HTML attribute in your templates. This enables dynamic updates to element attributes such as classes, styles, and other standard HTML attributes.
The basic syntax for binding to attributes in Aurelia is straightforward:
<div attribute-name.bind="value"></div>You can bind to almost any attribute listed in the comprehensive HTML attributes list, which can be found here.
Aurelia provides multiple methods for attribute binding, each with its syntax and use cases.
Interpolation allows for embedding dynamic values within strings. Here's an example using interpolation to bind the id attribute:
<div>
<h1 id="${headingId}">My Heading</h1>
</div>Aurelia supports several binding keywords, each defining the data flow between the view model and the view:
one-time: Updates the view from the view model once and does not reflect subsequent changes.
to-view / one-way: Continuously updates the view from the view model.
from-view: Updates the view model based on changes in the view.
two-way: Creates a two-way data flow, keeping the view and view model in sync.
bind: Automatically determines the appropriate binding mode, defaulting to two-way for form elements and to-view for most other elements.
<input type="text" value.bind="firstName">
<input type="text" value.two-way="lastName">
<input type="text" value.from-view="middleName">
<a class="external-link" href.bind="profile.blogUrl">Blog</a>
<a class="external-link" href.to-view="profile.twitterUrl">Twitter</a>
<a class="external-link" href.one-time="profile.linkedInUrl">LinkedIn</a>Binding image attributes, such as src and alt, is as simple as:
<img src.bind="imageSrc" alt.bind="altValue">Bind to the disabled attribute to disable buttons and inputs dynamically:
<button disabled.bind="disableButton">Disabled Button</button>Choose between innerhtml for rendering HTML content and textcontent for text-only content:
<div innerhtml.bind="htmlContent"></div>
<div textcontent.bind="textContent"></div>Aurelia uses a mapping function to convert properties to HTML attributes. The attribute mapper handles the conversion, typically changing kebab-case to camelCase. However, not all properties map directly to attributes.
.attr TagIf automatic mapping fails, use .attr to ensure proper attribute binding:
<input pattern.attr="patternProp">Apply the attribute binding behavior with .bind and & attr to specify the binding type:
<input pattern.bind="patternProp & attr">The <au-viewport> element is where all of the routing magic happens, the outlet. It supports a few different custom attributes, allowing you to configure how the router renders your components. It also allows you to use multiple viewports to create different layout configurations with your routing.
The router allows you to add multiple viewports to your application and render components into each viewport element by their name. The <au-viewport> element supports a name attribute, which you'll want to use if you have more than one.
<main>
<au-viewport name="main"></au-viewport>
</main>
<aside>
<au-viewport name="sidebar"></au-viewport>
</aside>In this example, we have the main viewport for our main content, and another viewport called sidebar for our sidebar content which is dynamically rendered. When using viewports, think of them like iframes, independent containers that can maintain their own states.
Routes will load in the default viewport element if there are one or more viewports. However, routes can be told to load into a specific viewport.
import { IRouteableComponent, routes } from '@aurelia/router';
@routes([
{
component: import('./my-component'),
path: 'my-component',
title: 'Your Component <3',
viewport: 'sidebar'
}
])
export class MyApp implements IRouteableComponent {
}By specifying the viewport property on a route, we can tell it to load into a specific route.
Learn how to style elements, components and other facets of an Aurelia application using classes and CSS. Strategies for different approaches are discussed in this section.
Aurelia makes it easy to modify an element inline class list and styles. You can work with not only strings but also objects to manipulate elements.
The class binding allows you to bind one or more classes to an element and its native class attribute.
Adding or removing a single class value from an element can be done using the .class binding. By prefixing the .class binding with the name of the class you want to display conditionally selected.class="myBool" you can add a selected class to an element. The value you pass into this binding is a boolean value (either true or false), if it is true the class will be added; otherwise, it will be removed.
<p selected.class="isSelected">I am selected (I think)</p>Inside of your view model, you would specify isSelected as a property and depending on the value, the class would be added or removed.
Here is a working example of a boolean value being toggled using .class bindings.
Unlike singular class binding, you cannot use the .class binding syntax to conditionally bind multiple CSS classes. However, there is a multitude of different ways in which this can be achieved.
class.bind="someString"
string
'col-md-4 bg-${bgColor}'
class="${someString}"
string
col-md-4 ${someString}
Once you have your CSS imported and ready to use in your components, there might be instances where you want to dynamically bind to the style attribute on an element (think setting dynamic widths or backgrounds).
You can dynamically add a CSS style value to an element using the .style binding in Aurelia.
<p background.style="bg">My background is blue</p>Inside of your view model, you would specify bg as a string value on your class.
Here is a working example of a style binding setting the background colour to blue:
To bind to one or more CSS style properties you can either use a string containing your style values (including dynamic values) or an object containing styles.
This is what a style string looks like, notice the interpolation here? It almost resembles just a plain native style attribute, with exception of the interpolation for certain values. Notice how you can also mix normal styles with interpolation as well?
export class MyApp {
private backgroundColor = 'black';
private textColor = '#FFF';
}<p style="color: ${textColor}; font-weight: bold; background: ${backgroundColor};">Hello there</p>You can also bind a string from your view model to the style property instead of inline string assignment by using style.bind="myString" where myString is a string of styles inside of your view model.
Styles can be passed into an element by binding to the styles property and using .bind to pass in an object of style properties. We can rewrite the above example to use style objects.
export class MyApp {
private styleObject = {
background: 'black',
color: '#FFF'
};
}<p style.bind="styleObject">Hello there</p>From a styling perspective, both examples above do the same thing. However, we are passing in an object and binding it to the style property instead of a string.
In Aurelia 2, templates are designed to limit direct access to global variables like window or document for security reasons. However, there are scenarios where access to certain global variables is necessary. Aurelia allows access to a predefined list of global variables commonly used in development.
To reduce boilerplate, Aurelia allows template expression to access a fixed list of global variables that are usually needed. Those globals are as follows:
Here are some examples of using globals inside of Aurelia templates. The usage is the same as it is inside of Javascript, except in your Aurelia templates.
Manipulate JSON data directly in your templates.
Perform calculations using the Math object.
isNaNDisplay content conditionally based on numeric checks.
RegExpUse the RegExp constructor to create dynamic regular expressions for data validation or manipulation.
ObjectAccess properties dynamically on an object using the Object constructor.
SetDemonstrate set operations like union, intersection, or difference.
encodeURI and decodeURIManipulate URL strings by encoding or decoding them.
Intl.NumberFormatFormat numbers using Intl.NumberFormat for localization.
ArrayDemonstrate complex array manipulations, such as chaining methods.
Use Sparingly: Rely on global variables only when necessary. Prefer component properties and methods for data and logic.
Security: Be cautious of the data processed using global functions to prevent XSS attacks and other vulnerabilities.
Performance: Frequent use of complex operations like JSON.stringify in templates can impact performance. Consider handling such operations in the component class.
Reactivity: Remember that changes to global variables are not reactive. If you need reactivity, use component properties or state management solutions.
The Observer Locator API allows you to watch properties in your components for changes without the need for using the @observable decorator. In most cases, manual observation will not be required using this API, but it is there if you want it.
By default, an observer locator is used to create observers and subscribe to them for change notification.
A basic observer has the following interface:
The subscribe method of an observer can be used to subscribe to the changes that it observes. This method takes a subscriber as its argument.
A basic subscriber has the following interface:
An observer of an object property can be retrieved using an observer locator.
An example of this is:
And to subscribe to changes emitted by this observer:
It's not always sufficient to observe a single property on an object, and it's sometimes more desirable to return a computed value from the source so that subscribers of an observer don't have to perform any logic dealing with the updated values. An example of this is the follow observation of firstName and lastName to notify full name:
Doing it the way above is cumber some as we need to setup 2 observers and 2 subscribers, also there's a typo risk. We can also use a getter to express a computed value, and then observe that getter to avoid having to do heavy setup work:
This is not always feasible since the obj could be from a 3rd party library, or some json data from server, and the risk of having a typo fullName is still there.
Aurelia provides another API of creating observer to deal with this scenario, where it's more desirable to use a function/lambda expression to express the dependencies and computed value to notify the subscriber. To use this API, replace the 2nd parameter of getObserver with a getter function to express the value:
Errors 0001 to 0015 are Dependency Injection errors.
Please see below a reference to each related error with explanations and resources for debugging and solving.
Infinity
NaN
isFinite
isNaN
parseFloat
parseInt
decodeURI
decodeURIComponent
encodeURI
encodeURIComponent
Array
BigInt
Boolean
Date
Map
Number
Object
RegExp
Set
String
JSON
Math
Intl<template>
<pre>${JSON.stringify(user, null, 2)}</pre>
</template><template>
<p>The square root of 16 is ${Math.sqrt(16)}</p>
</template><template>
<p if.bind="isNaN(value)">Not a number</p>
</template><template>
<input value.bind="email" type="email" placeholder="Enter email">
<p if.bind="new RegExp('^\\S+@\\S+\\.\\S+$').test(email)">Valid Email Address</p>
</template><template>
<p>Property Value: ${Object.getOwnPropertyDescriptor(user, selectedProperty)?.value}</p>
</template><template>
<p>Unique Numbers: ${[...new Set(numbersArray)]}</p>
</template><template>
<a href.bind="encodeURI(externalLink)">Visit External Site</a>
<p>Original URL: ${decodeURI(externalLink)}</p>
</template><template>
<p>${new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price)}</p>
</template><template>
<p>Processed Data: ${Array.from(dataSet).filter(x => x.isActive).map(x => x.value).join(', ')}</p>
</template>interface IObserver {
subscribe(subscriber)
unsubscribe(subscriber)
}interface ISubscriber {
handleChange(newValue, oldValue)
}// getting the observer for property 'value'
const observer = observerLocator.getObserver(obj, 'value')const subscriber = {
handleChange(newValue) {
console.log('new value of object is:', newValue)
}
}
observer.subscribe(subscriber)
// and to stop subscribing
observer.unsubscribe(subscriber)const obj = { firstName: '', lastName: '' }
function notifyFullnameChanged() {
console.alert(`${obj.firstName} ${obj.lastName}`);
}
const observer1 = observerLocator.getObserver(obj, 'firstName').subscribe({ handleChange: notifyFullnameChanged })
const observer2 = observerLocator.getObserver(obj, 'lastName').subscribe({ handleChange: notifyFullnameChanged })const obj = { firstName: '', lastName: '', get fullName() { return `${this.firstName} ${this.lastName}` } }
const observer = observerLocator.getObserver(obj, 'fullName').subscribe({ handleChange: fullname => alert(fullname) });const obj = { firstName: '', lastName: '' }
const observer = observerLocator.getObserver(obj, obj => `${obj.firstName} ${obj.lastName}`).subscribe({
handleChange: fullname => alert(fullname)
});Learn how to navigate the router programmatically using the router load method and the HTML load attribute for creating in-page routes.
This section details how you can use the load method on the router instance or load attribute to navigate to other parts of your application.
To use the load method, you have first to inject the router into your component. This can be done easily by using the IRouter decorator on your component constructor method. The following code will add a property to your component, which we can reference.
import { IRouter, IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
constructor(@IRouter private router: IRouter) {
}
}The load method can accept a simple string value allowing you to navigate to another component without needing to supply configuration options.
import { IRouter, IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
constructor(@IRouter private router: IRouter) {
}
async viewProducts() {
await this.router.load('/products');
}
}You could also use the string value method to pass parameter values and do something like this where our route expects a product ID, and we pass 12:
import { IRouter, IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
constructor(@IRouter private router: IRouter) {
}
async viewProducts() {
await this.router.load(`/products/12`);
}
}The router instance load method allows you to specify different properties on a per-use basis. The most common one is the title property, which allows you to modify the title as you navigate your route.
A list of available load options can be found below:
title — Sets the title of the component being loaded
parameters — Specify an object to be serialized to a query string and then set to the query string of the new URL.
fragment — Specify the hash fragment for the new URL.
These option values can be specified as follows and when needed:
import { IRouter, IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
constructor(@IRouter private router: IRouter) {
}
async viewProduct() {
await this.router.load('products', {
title: 'My product',
parameters: {
prop1: 'val',
tracking: 'asdasdjaks232'
},
fragment: 'jfjdjf'
});
}
}The router also allows you to decorate links and buttons in your application using a load attribute, which works the same way as the router instance load method.
If you have routes defined on a root level (inside of my-app.ts) you will need to add a forward slash in front of any routes you attempt to load. The following would work in the case of an application using configured routes.
<a load="/products/12">Product #12</a>The load attribute can do more than accept a string value. You can also bind to the load attribute for more explicit routing. The following example is a bit redundant as specifying route:product would be the same as specifying load="product" , but if you're wanting more explicit routing, it conveys the intent better.
<a load="route:product;">My Route</a>And where things start to get interesting is when you want to pass parameters to a route. We use the params configuration property to specify parameters.
<a load="route:profile; params.bind:{name: 'rob'}">View Profile</a>In the above example, we provide the route (id) value (via route: profile). But, then also provide an object of parameters (via params.bind: { name: 'rob' }).
These parameter values correspond to any parameters configured in your route definition. In our case, our route looks like this:
{
id: 'profile',
path: 'profile/:name',
component: () => import('./view-profile'),
title: 'View Profile'
},Depending on the scenario, you will want to redirect users in your application. Unlike using the load API on the router where we manually route (for example, after logging in) redirection allows us to redirect inside router hooks.
Please see the Routing Lifecycle section to learn how to implement redirection inside your components.
Install via npm
npm install @aurelia/ui-virtualizationLoad the plugin
import { Aurelia } from 'aurelia';
import { DefaultVirtualizationConfiguration } from '@aurelia/ui-virtualization';
Aurelia
.register(DefaultVirtualizationConfiguration)
.app(...)Simply bind an array to virtual-repeat like you would with the standard repeat. The repeated rows are expected to have equal height throughout the list, and one item per row.
<template>
<div virtual-repeat.for="item of items">
${$index} ${item}
</div>
</template><template>
<ul>
<li virtual-repeat.for="item of items">
${$index} ${item}
</li>
</ul>
</template><template>
<table>
<tr virtual-repeat.for="item of items">
<td>${$index}</td>
<td>${item}</td>
</tr>
</table>
</template>export class MyVirtualList {
items = ['Foo', 'Bar', 'Baz'];
}With a surrounding fixed height container with overflow scroll. Note that overflow: scroll styling is inlined on the elemenet. It can also be applied from CSS. An error will be thrown if no ancestor element with style overflow: scroll is found.
<template/> is not supported as root element of a virtual repeat template. This is due to the difficulty of technique employed: item height needs to be calculatable. With <tempate/>, there is no easy and performant way to acquire this value.
Similar to (1), other template controllers cannot be used in conjunction with virtual-repeat, unlike repeat. I.e: built-in template controllers: with, if, etc... cannot be used with virtual-repeat. This can be workaround'd by nesting other template controllers inside the repeated element, with <template/> element, for example:
<template>
<h1>${message}</h1>
<div virtual-repeat.for="person of persons">
<template with.bind="person">
${Name}
</template>
</div>
</template>Beware of CSS selector :nth-child and similar selectors. Virtualization requires appropriate removing and inserting visible items, based on scroll position. This means DOM elements order will not stay the same, thus creating unexpected :nth-child CSS selector behavior. To work around this, you can use contextual properties $index, $odd, $even etc... to determine an item position, and apply CSS classes/styles against it, like the following example:
<template>
<div virtual-repeat.for="person of persons" class="${$odd ? 'odd' : 'even'}-row">
${person.name}
</div>
</template>Similar to (3), virtualization requires appropriate removing and inserting visible items, so not all views will have their lifecycle invoked repeatedly. Rather, their binding contexts will be updated accordingly when the virtual repeat reuses the view and view model. To work around this, you can have your components work in a reactive way, which is natural in an Aurelia application. An example is to handle changes in change handler callback.
Aurelia allows you to configure the application startup in a couple of different ways. A quick setup where some defaults are assumed and a verbose setup where you can configure some of the framework-specific behaviors.
The quick startup approach is what most developers will choose.
import { RouterConfiguration } from '@aurelia/router';
import Aurelia, { StyleConfiguration } from 'aurelia';
import { MyRootComponent } from './my-root-component';
// By default host to element name (<my-root-component> for MyRootComponent),
// or <body> if <my-root-component> is absent.
Aurelia.app(MyRootComponent).start();
// Or load additional Aurelia features
Aurelia
.register(
RouterConfiguration.customize({ useUrlFragmentHash: false })
)
.app(MyRootComponent)
.start();
// Or host to <my-start-tag>
Aurelia
.register(
RouterConfiguration.customize({ useUrlFragmentHash: false })
)
.app({
component: MyRootComponent,
host: document.querySelector('my-start-tag')
})
.start();To start an Aurelia application, create a new Aurelia() object with a target host and a root component and call start().
import Aurelia, { StandardConfiguration } from 'aurelia';
import { ShellComponent } from './shell';
new Aurelia()
.register(StandardConfiguration)
.app({ host: document.querySelector('body'), component: ShellComponent })
.start();In most instances, you will not use the verbose approach to starting your Aurelia applications. The verbose approach is more aimed at developers integrating Aurelia into existing web applications and views.
To make a custom element globally available to your application, pass the custom element constructor to the .register() method on your Aurelia app.
import { CardCustomElement } from './components/card';
// When using quick startup
Aurelia
.register(...)
.register(<any>CardCustomElement);
.app({ ... })
.start();
// When using verbose startup
new Aurelia()
.register(...)
.register(<any>CardCustomElement)
.app({ ... })
.start();If you have a package that exports all your custom elements, you can pass the entire package to the .register() method on your Aurelia app.
src/components/index.ts:
export { CardCustomElement } from './card';
export { CollapseCustomElement } from './collapse';src/main.ts:
import * as globalComponents from './components';
// When using quick startup
Aurelia
.register(...)
.register(<any>globalComponents)
.app({ ... })
.start();
// When using verbose startup
new Aurelia()
.register(...)
.register(<any>globalComponents)
.app({ ... })
.start();Aurelia provides a powerful logging API that allows you to display debug and error messages in your applications in a controlled manner.
Aurelia comes with a flexible and powerful logging system that allows you to display debug and error messages in your applications in a slightly better way than using native console.log statements.
Reasons to use logging inside of your apps and plugins include helpful debug messages for other developers (living comments) or displaying helpful information to the end-user in the console when something goes wrong.
The logger is injected using dependency injection into your components:
import { ILogger } from 'aurelia';
export class MyComponent {
public constructor(@ILogger private readonly logger: ILogger) {
this.logger = logger.scopeTo('MyComponent');
}
}In this example, we scope our logger to our component. But scoping is optional, and the logger can be used without using scopeTohowever, we highly recommend using the scoping feature to group your messages in the console.
Just like console.log the Aurelia logger supports the following methods:
debug
info
warn
trace
These methods are called on the logger instance you injected into your component.
import { ILogger } from 'aurelia';
export class MyComponent {
public constructor(@ILogger private readonly logger: ILogger) {
this.logger = logger.scopeTo('MyComponent');
}
public add() {
this.logger.debug(`Adding something`);
}
}Just like console.log you can also pass in values such as strings, booleans, arrays and objects.
import { ILogger } from 'aurelia';
export class MyComponent {
public constructor(@ILogger private readonly logger: ILogger) {
this.logger = logger.scopeTo('MyComponent');
}
public add() {
this.logger.debug(`Adding something`, [
{ prop: 'value', something: 'else' }
]);
}
}To create a custom logger for your applications and plugins, you can create a more reusable wrapper around the logging APIs to use in your applications.
import { DI, ILogger, ConsoleSink, IPlatform, LogLevel, LoggerConfiguration, Registration } from '@aurelia/kernel';
import { BrowserPlatform } from '@aurelia/platform-browser';
const PLATFORM = BrowserPlatform.getOrCreate(globalThis);
const staticContainer = DI.createContainer();
staticContainer.register(Registration.instance(IPlatform, Registration));
staticContainer.register(LoggerConfiguration.create({ sinks: [ConsoleSink], level: LogLevel.fatal }));
export const log = staticContainer.get(ILogger).scopeTo('My App');
It might look like a lot of code, but this logger implementation will create a scoped logger wrapper you can import into your applications and use in the following way:
log.debug(`Debug message`);
log.warn(`This is a warning`);Aurelia's testing library enhances the developer experience by offering a Fluent API for creating test fixtures. This API provides a more readable, flexible, and chainable way to set up component tests. With the Fluent API, you can incrementally build your test fixture, making the configuration of your tests more intuitive and maintainable.
The Fluent API for createFixture comprises a series of chainable methods that allow you to configure each aspect of your test fixture in a step-by-step manner. This methodical approach to building test fixtures is particularly beneficial when dealing with complex setups or when you need to express the configuration in a more descriptive way.
Previously, creating a test fixture required passing all configuration parameters to the createFixture function in a single call, which could become unwieldy as the number of configurations grew:
const { appHost, startPromise, tearDown } = await createFixture('<my-element></my-element>', class AppRoot {}, [Dependency1, Dependency2]).promise;With the introduction of the Fluent API, you can now configure your test fixture using several self-explanatory methods, each responsible for a specific part of the setup:
const fixture = createFixture
.component(AppRoot)
.deps(Dependency1, Dependency2)
.html('<my-element></my-element>');
const { appHost, startPromise } = await fixture.build().start();The Fluent API provides the following methods, which can be chained together to configure your test fixture:
.component(component: any): Specifies the root component class for the test fixture.
.deps(...dependencies: any[]): Registers additional dependencies required by the test or the components under test.
.html(template: string | HTMLTemplateElement): Sets the HTML template for the test. This can be provided as a string literal, a tagged template literal, or an HTMLTemplateElement.
.build(): Finalizes the configuration and builds the test fixture.
.start(): Initializes the test fixture and returns a promise that resolves when the component is bound and attached.
Consider you have a MyCustomElement that relies on Dependency1 and Dependency2. The following example demonstrates how to use the Fluent API to create a test fixture for this component:
import { MyCustomElement } from './my-custom-element';
import { Dependency1, Dependency2 } from './dependencies';
import { createFixture } from '@aurelia/testing';
describe('MyCustomElement', () => {
it('renders correctly', async () => {
// Incrementally configure the test fixture using the Fluent API
const fixture = createFixture
.component(MyCustomElement)
.deps(Dependency1, Dependency2)
.html('<my-custom-element></my-custom-element>');
// Build and start the fixture
const { appHost, startPromise } = await fixture.build();
// Await the startPromise to ensure the component is fully initialized
await startPromise;
// Perform assertions on appHost to verify the correct rendering of MyCustomElement
expect(appHost.querySelector('my-custom-element')).toBeDefined();
expect(appHost.textContent).toContain('Expected content');
// Additional assertions and test logic...
});
});In this example, the Fluent API clearly outlines each step of the test fixture setup. It begins by defining the component under test, registers any dependencies, and sets the HTML template. Finally, the fixture is built and started, and the test awaits the startPromise before performing assertions.
The Fluent API offers several advantages over the traditional approach:
Readability: The step-by-step configuration makes the test setup easier to read and understand.
Maintainability: It's easier to update and maintain tests as configurations can be changed independently without affecting the entire setup.
Flexibility: The API allows for dynamic adjustments to the test setup, accommodating various testing scenarios.
By employing the Fluent API, developers can write more coherent and expressive tests, enhancing the overall testing experience in Aurelia 2 applications.
The Aurelia template compiler is powerful and developer-friendly, allowing you extend its binding language with great ease.
The Aurelia binding language provides commands like .bind, .one-way, .trigger, .for, .class etc. These commands are used in the view to express the intent of the binding, or in other words, to build binding instructions.
Although the out-of-box binding language is sufficient for most use cases, Aurelia also provides a way to extend the binding language so that developers can create their own incredible stuff when needed.
In this article, we will build an example to demonstrate how to introduce your own binding commands using the @bindingCommand decorator.
Before jumping directly into the example, let's first understand what a binding command is. In a nutshell, a binding command is a piece of code used to register "keywords" in the binding language and provide a way to build binding instructions from that.
To understand it better, we start our discussion with the template compiler. The template compiler is responsible for parsing templates and, among all, creating attribute syntaxes. This is where the attribute patterns come into play. Depending on how you define your attribute patterns, the attribute syntaxes will be created with or without a binding command name, such as bind, one-way, trigger, for, class, etc. The template compiler then instantiates binding commands for the attribute syntaxes with a binding command name. Later, binding instructions are built from these binding commands, which are "rendered" by renderers. Depending on the binding instructions, the " rendering " process can differ. For this article, the rendering process details are unimportant, so we will skip it.
To create a binding command, we use the @bindingCommand decorator with a command name on a class that implements the following interface:
interface BindingCommandInstance {
type: CommandType;
build(info: ICommandBuildInfo, parser: IExpressionParser, mapper: IAttrMapper): IInstruction;
}A binding command must return 'IgnoreAttr' from the type property. This tells the template compiler that the binding command takes over the processing of the attribute.
The more interesting part of the interface is the build method. The template compiler calls this method to build binding instructions. The info parameter contains information about the element, the attribute name, the bindable definition (if present), and the custom element/attribute definition (if present). The parser parameter is used to parse the attribute value into an expression. The mapper parameter of type IAttrMapper is used to determine the binding mode, the target property name, etc. (for more information, refer to the documentation). In short, here comes your logic to convert the attribute information into a binding instruction.
For our example, we want to create a binding command that can trigger a handler when custom events such as bs.foo.bar, bs.fizz.bizz etc. is fired, and we want the following syntax:
<div foo.bar.bs="ev => handleCustomEvent(ev)"></div>instead of
<div bs.foo.bar.trigger="ev => handleCustomEvent(ev)"></div>We first create a class that implements the BindingCommandInstance interface to do that.
import { IExpressionParser } from '@aurelia/runtime';
import {
BindingCommandInstance,
ICommandBuildInfo,
IInstruction,
ListenerBindingInstruction,
bindingCommand,
} from '@aurelia/runtime-html';
@bindingCommand('bs')
export class BsBindingCommand implements BindingCommandInstance {
public get type(): 'IgnoreAttr' {
return 'IgnoreAttr';
}
public build(
info: ICommandBuildInfo,
exprParser: IExpressionParser
): IInstruction {
return new ListenerBindingInstruction(
/* from */ exprParser.parse(info.attr.rawValue, 'IsFunction'),
/* to */ `bs.${info.attr.target}`,
/* preventDefault */ true,
/* capture */ false
);
}
}Note that from the build method, we are creating a ListenerBindingInstruction with bs. prefixed to the event name used in the markup. Thus, we are saying that the handler should be invoked when a bs.* event is raised.
To register the custom binding command, it needs to be registered with the dependency injection container.
And that's it! We have created our own binding command. This means that the following syntax will work.
<div foo.bar.bs="ev => handleCustomEvent(ev)"></div>
<!-- ^^
|_________ custom binding command
-->This binding command can be seen in action below.
Note that the example defines a custom attribute pattern to support
foo.bar.fizz.bs="ev => handle(ev)"syntax.
Strategies for stateful router animation
A common scenario in a single-page application is page transitions. When a page loads or unloads, an animation or transition effect might be used to make it feel more interactive and app-like.
By leveraging lifecycle hooks, we can perform animations and transition effects in code.
import { lifecycleHooks } from '@aurelia/runtime-html';
import anime from 'animejs';
const animateIn = (element) =>
anime({
targets: element,
translateX: () => ['110%', '0%'],
duration: 900,
easing: 'easeInOutQuart',
});
const animateOut = (element) =>
anime({
targets: element,
translateX: () => ['0%', '110%'],
duration: 900,
easing: 'easeInOutQuart',
});
@lifecycleHooks()
export class AnimationHooks {
private element;
private backwards = false;
public created(vm, controller): void {
this.element = controller.host;
}
public loading(vm, _params, _instruction, navigation) {
this.backwards = navigation.navigation.back;
}
public unloading(vm, _instruction, navigation) {
this.backwards = navigation.navigation.back;
}
public attaching() {
if (this.backwards) {
animateOut(this.element);
} else {
animateIn(this.element);
}
}
public detaching() {
if (this.backwards) {
animateIn(this.element);
} else {
animateOut(this.element);
}
}
}At first glance, this might look like a lot of code, but we do the animation inside of the attaching and detaching hooks. Using the Anime.js animation library, we create two animation functions for sliding our views in and out.
We use the created lifecycle callback to access the host element (the outer element of our custom element) which we will animate. Most of the other callbacks determine the direction we are heading in.
import { One } from './one';
import { Two } from './two';
import { AnimationHooks } from './animation-hooks';
export class MyApp {
static dependencies = [AnimationHooks];
public static routes = [
{ path: ['', 'one'], component: One },
{ path: 'two', component: Two },
];
public message: string = 'Hello Aurelia 2!';
}peWe inject out AnimationHooks class into our main component, but we also inject it into the sub-components we want to animate. We avoid setting our hook globally, or it would run for all components (which you might want).
As you can see, besides some router-specific lifecycle methods, animating with the router isn't router-specific and leverages Aurelia lifecycles.
A link to a demo of slide in and out animations based on routing can be seen below:
Learn how to use Aurelia with existing HTML (inside of other frameworks and libraries), hydrating server-generated HTML or running multiple instances of Aurelia in your application.
Enhancement in Aurelia allows for integrating Aurelia’s capabilities with existing DOM elements or dynamically inserted HTML content. This feature is particularly useful in scenarios where the application is not entirely built with Aurelia, such as when integrating with server-rendered pages or dynamically generated content.
The showed how to start Aurelia for an empty root node. While that's the most frequent use case, there might be other scenarios where we would like to work with an existing DOM tree with Aurelia.
The basic usage of enhance is straightforward:
Key Points to Understand:
Anonymous Custom Element Hydration: The enhancement treats the target node as an anonymous custom element, allowing Aurelia to apply its behavior to the existing DOM structure.
Component Flexibility: The component parameter in enhance can be a custom element class, a class instance, or an object literal. If a class is provided, it's instantiated by Aurelia's dependency injection container, which can be either provided or automatically created.
Host Element: The host is typically an existing DOM node that is not yet under Aurelia's control. It's crucial to note that enhance ' neither detaches nor attaches the hostto the DOM. Existing event handlers on thehost` or its descendants remain unaffected.
Controller Deactivation: an enhance call results in an application root that requires manual deactivation or integration into an existing controller hierarchy for automatic framework management.
Example of deactivating an application root:
Enhance can be particularly useful during application startup, especially when integrating Aurelia into an existing web page or alongside other frameworks.
Let's create an index.html file containing some HTML markup you would encounter if you generated an Aurelia application using npx makes aurelia or other means.
Pay attention to the contents of the <body> as there is a container called app as well as some HTML tags <my-app>
Now, let's enhance our application by using the enhanceAPI inside of main.ts
Or if your component has one of its lifecycle return a promise:
We first wrap our async code in an anonymous async function. This allows us to catch errors and throw them to the console if enhancement fails, but take note of the enhance call itself. We supply the host element (in our case, it's a DIV with an ID of app as the host).
Above our enhance call, we register our main component, MyApp, the initial component our application will render.
Pay attention to what you are enhancing. Please make sure you are enhancing the container and not the component itself. It's an easy mistake, and we have seen some developers get caught on.
This approach will work for existing applications as well. Say you have a WordPress website and want to create an Aurelia application on a specific page. You could create a container and pass the element to the host on the enhance call.
While using the enhance during registration, the enhance API is convenient for situations where you want to control how an Aurelia application is enhanced. There are times when you want to enhance HTML programmatically from within components. This may be HTML loaded from the server or elements created on the fly.
In the following example, we query our markup for an item-list element and insert some Aurelia-specific markup into it (a repeater).
As you can see, we are dynamically injecting some HTML into an existing element. Because this is being done after Aurelia has already compiled the view, it would not work. This is why we must call enhance to tell Aurelia to parse our inserted HTML.
You can use this approach to enhance HTML inserted into the page after initial compilation, which is perfect for server-generated code.
Create a navigation menu using navigation model in Router-Lite.
The navigation model can be thought of as view-friendly version of the configured routes. It provides similar information as of the configured routes with some additional data to it. This is typically useful when you want to create navigation menu from the already registered/configured routes in the router, without necessarily duplicating the data. The information takes the following shape.
Note that apart from , all other properties of the route object are same as the corresponding configured route.
This section provides example of how to use navigation model while discussing different aspects of it.
The following example shows how to create a navigation menu using the info from the navigation model.
In this example, we are using a custom element named nav-bar. In the custom element we inject an instance of IRouteContext and we grab the navigation model from the routing context.
Then the information from the model is used in the view to create the navigation menu.
It additionally shows that from the NavBar#binding, INavigationModel#resolve() is awaited. This is recommended, when dealing with async route configuration. This allows all the promises to be resolved and thereafter building the navigation information correctly.
isActive propertyThe isActive property is true when this route is currently active (loaded), and otherwise it is false. A typical use-case for this property is to apply or remove the "active" style to the links, depending on if the link is active or not. You can see this in the following example where a new .active class is added and that is bound to the isActive property.
You can see this in action below.
By default, all configured routes are added to the navigation model. However, there might be routes which is desired to be excluded from the navigation model; for example: a fallback route for un-configured routes. To this end, a route can be configured with nav: false to instruct the router not to included it in the navigation model.
You see this in action in the example below.
If you are not creating a menu using the navigation model, you can also deactivate the navigation model by setting false to the useNavigationModel . Doing so, will set the IRouteContext#navigationModel to null and skip further processing.
Testing custom attributes in Aurelia is analogous to testing components, with the primary difference being that custom attributes do not have a view template. They are, however, responsible for modifying the behavior or appearance of existing DOM elements. By leveraging the same testing techniques used for components, we can effectively validate the functionality of our custom attributes.
Let's consider a ColorSquareCustomAttribute that we previously created. This attribute applies a color border and sets the size of an element, resulting in a square of uniform dimensions with a colored background.
We will now write tests to ensure that the ColorSquareCustomAttribute behaves as expected when applied to an element.
Before writing tests, ensure that your test environment is properly configured. The setup for testing custom attributes is the same as for components, so refer to the section.
Create a test file for your custom attribute, such as color-square.spec.ts, and use the following example as a guide:
In the first test, we verify that the default size and color are applied to an element when the custom attribute is used without any bindings. In the second test, we bind the color and size properties and then change the color to ensure the colorChanged method updates the element's style as expected.
As with components, we use createFixture to set up our test environment. The first argument is the HTML view where we use our custom attribute. The second argument is the view model, which can define values to bind in our view model if needed. The third argument specifies any dependencies required by our tests, such as custom elements, value converters, or attributes.
Testing custom attributes in Aurelia 2 is essential to ensure they correctly manipulate DOM elements as intended. By setting up a proper testing environment, creating fixtures, and writing assertions, we can confidently verify that our custom attributes perform their duties correctly. Always remember to clean up your tests to maintain a pristine testing state.
const au = new Aurelia();
await au.enhance({ host, component: MyComponent });const root = au.enhance({ host, component });
root.deactivate();<body>
<div id="app">
<my-app></my-app>
</div>
</body>import Aurelia from 'aurelia';
import { MyApp } from './my-app';
try {
Aurelia
.register(MyApp)
.enhance({
host: document.querySelector('div#app'),
component: {},
});
} catch (error) {
console.error(error);
}import Aurelia from 'aurelia';
import { MyApp } from './my-app';
;(async () => {
try {
await Aurelia
.register(MyApp)
.enhance({
host: document.querySelector('div#app'),
component: {},
});
} catch (error) {
console.error(error);
}
})();import Aurelia, { IAurelia, resolve } from 'aurelia';
export class MyApp {
items = [1, 2, 3];
constructor(private readonly au = resolve(Aurelia)) {}
attached() {
const itemList = document.getElementById('item-list');
itemList.innerHTML = "<div repeat.for='item of items'>${item}</div>";
this.au.enhance({
component: { items: this.items },
host: itemList,
});
}
}import { bindable, customAttribute, INode } from 'aurelia';
@customAttribute('color-square')
export class ColorSquareCustomAttribute {
@bindable color: string = 'red';
@bindable size: string = '100px';
constructor(@INode private element: HTMLElement) {
this.element.style.width = this.size;
this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.width = this.size;
this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
colorChanged(newColor: string) {
this.element.style.backgroundColor = newColor;
}
sizeChanged(newSize: string) {
this.element.style.width = newSize;
this.element.style.height = newSize;
}
}import { createFixture } from '@aurelia/testing';
import { ColorSquareCustomAttribute } from './color-square';
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';
describe('ColorSquareCustomAttribute', () => {
beforeAll(() => {
// Initialize the test environment before running the tests
bootstrapTestEnvironment();
});
it('applies default width and color', async () => {
const { appHost, startPromise, tearDown } = createFixture(
'<div id="attributeel" color-square></div>',
class App {},
[ColorSquareCustomAttribute]
);
await startPromise;
const el = appHost.querySelector('#attributeel') as HTMLElement;
expect(el.style.width).toBe('100px');
expect(el.style.height).toBe('100px');
expect(el.style.backgroundColor).toBe('red');
await tearDown();
});
it('reacts to color changes', async () => {
const { appHost, component, startPromise, tearDown } = createFixture(
'<div color-square="color.bind: newColor; size.bind: newSize"></div>',
class App {
newColor = 'blue';
newSize = '150px';
},
[ColorSquareCustomAttribute]
);
await startPromise;
const colorSquareAttribute = component.viewModel as ColorSquareCustomAttribute;
// Test initial state
expect(appHost.firstElementChild.style.backgroundColor).toBe('blue');
expect(appHost.firstElementChild.style.width).toBe('150px');
expect(appHost.firstElementChild.style.height).toBe('150px');
// Change color property
colorSquareAttribute.color = 'green';
colorSquareAttribute.colorChanged('green', 'blue');
expect(appHost.firstElementChild.style.backgroundColor).toBe('green');
await tearDown();
});
// Additional tests...
});Learn about the various methods for conditionally rendering content in Aurelia 2, with detailed explanations and examples.
Conditional rendering in Aurelia 2 is a powerful feature that lets you create dynamic interfaces that respond to your application's state. You can conditionally include or exclude parts of your view using boolean expressions. This guide will walk you through the different techniques provided by Aurelia to manage conditional content.
if.bindThe if.bind directive allows you to conditionally add or remove elements from the DOM based on the truthiness of the bound expression.
When the bound value evaluates to false, Aurelia removes the element and its descendants from the DOM. This process includes the destruction of custom elements, detaching of events, and cleanup of any associated resources, which is beneficial for performance and memory management.
Consider an application where you want to display a loading message while data is being fetched:
<div if.bind="isLoading">Loading...</div>The isLoading variable controls the presence of the div in the DOM. When it's true, the loading message appears; when false, the message is removed.
if.bind with elseAurelia enables if/else structures in the view, similar to conditional statements in JavaScript. The else binding must immediately follow an element with if.bind:
<div if.bind="user.isAuthenticated">Welcome back, ${user.name}!</div>
<div else>Please log in.</div>This snippet displays a welcome message for authenticated users and a login prompt for others.
Be mindful that if.bind modifies the DOM structure, which can trigger reflow and repaint processes in the browser. For applications with extensive DOM manipulation, this may become a performance bottleneck. Optimize your usage of if.bind by minimizing the frequency and complexity of conditional rendering operations.
show.bindThe show.bind directive offers an alternative approach to conditional rendering. Instead of adding or removing elements from the DOM, it toggles their visibility. This is akin to applying display: none; in CSS—the element remains in the DOM but is not visible to the user.
<div show.bind="isDataLoaded">Data loaded successfully!</div>Here, isDataLoaded dictates the visibility of the message. When false, the message is hidden; when true, it is shown. All bindings and events remain intact since the element is not removed from the DOM.
switch.bindFor more complex conditional rendering cases, such as when dealing with enumerated values, switch.bind is the ideal choice. It offers a clean, semantic way to handle multiple conditions by mimicking the switch statement in JavaScript.
For instance, given an enumeration of order statuses:
enum Status {
Received = 'received',
Processing = 'processing',
Dispatched = 'dispatched',
Delivered = 'delivered',
Unknown = 'unknown',
}Displaying a message based on the order status with if.bind can become unwieldy. Instead, switch.bind offers a concise and clear approach:
<template switch.bind="orderStatus">
<span case="received">Order received.</span>
<span case="processing">Processing your order.</span>
<span case="dispatched">On the way.</span>
<span case="delivered">Delivered.</span>
<span default-case>Status unknown.</span>
</template>This structure allows for a straightforward mapping between the status and the corresponding message. The default-case acts as a catch-all for any status not explicitly handled.
You can bind an array of values to a case, thus grouping multiple conditions:
<template switch.bind="orderStatus">
<span case.bind="['received', 'processing']">Order is being processed.</span>
<span case="dispatched">On the way.</span>
<span case="delivered">Delivered.</span>
</template>This will display "Order is being processed." for both Received and Processing statuses.
The switch construct in Aurelia supports fall-through logic similar to JavaScript's switch:
<template switch.bind="orderStatus">
<span case="received" fall-through.bind="true">Order received.</span>
<span case="processing">Order is being processed.</span>
<!-- Other cases -->
</template>When orderStatus is Received, both the "Order received." and "Order is being processed." messages will be displayed because of the fall-through attribute.
switch.bindAurelia's switch.bind can accommodate various advanced use cases, making it a versatile tool for conditional rendering. Below are examples of such scenarios:
switch.bind with Static ExpressionsYou can use switch.bind with a static expression, while the case.bind attributes feature more dynamic conditions:
<template repeat.for="num of 100">
<template switch.bind="true">
<span case.bind="num % 3 === 0 && num % 5 === 0">FizzBuzz</span>
<span case.bind="num % 3 === 0">Fizz</span>
<span case.bind="num % 5 === 0">Buzz</span>
</template>
</template>This example iterates over numbers 0 to 99 and applies the FizzBuzz logic, displaying "Fizz", "Buzz", or "FizzBuzz" depending on whether the number is divisible by 3, 5, or both.
switch.bindswitch.bind can be combined with au-slot to project content into custom elements conditionally:
<template as-custom-element="foo-bar">
<au-slot name="s1"></au-slot>
</template>
<foo-bar>
<template au-slot="s1" switch.bind="status">
<span case="received">Order received.</span>
<span case="dispatched">On the way.</span>
<span case="processing">Processing your order.</span>
<span case="delivered">Delivered.</span>
</template>
</foo-bar>In this case, the custom element foo-bar will project different messages based on the status value.
switch.bindswitch.bind can be nested within itself for complex conditional logic:
<template>
<let day.bind="2"></let>
<template switch.bind="status">
<span case="received">Order received.</span>
<span case="dispatched">On the way.</span>
<span case="processing">Processing your order.</span>
<span case="delivered" switch.bind="day">
Expected to be delivered
<template case.bind="1">tomorrow.</template>
<template case.bind="2">in 2 days.</template>
<template default-case>in a few days.</template>
</span>
</template>
</template>This example demonstrates how you can use nested switch.bind statements to handle multiple levels of conditional rendering.
case UsageThe case attribute must be used within the context of a switch and should be its direct child. The following are examples of incorrect and unsupported usages:
<!-- Incorrect: `case` outside of `switch` context -->
<span case="foo"></span>
<!-- Incorrect: `case` not a direct child of `switch` -->
<template switch.bind="status">
<template if.bind="someCondition">
<span case="delivered">Delivered</span>
</template>
</template>These examples will either throw an error or result in unexpected behavior. If you need to support a use case like this, consider reaching out to the Aurelia team.
By exploring these advanced scenarios, you can harness the full potential of switch.bind to address complex conditional rendering needs in your Aurelia applications. Remember to adhere to the guidelines and limitations to ensure proper functionality and maintainability.
The Aurelia template compiler is powerful and developer-friendly, allowing you extend its syntax with great ease.
Sometimes you will see the following template in an Aurelia application:
<input value.bind="message">Aurelia understands that value.bind="message" means value.two-way="message", and later creates a two way binding between view model message property, and input value property. How does Aurelia know this?
By default, Aurelia is taught how to interpret a bind binding command on a property of an element via a Attribute Syntax Mapper. Application can also tap into this class to teach Aurelia some extra knowledge so that it understands more than just value.bind on an <input/> element.
You may sometimes come across some custom input element in a component library, some examples are:
Microsoft FAST text-field element: https://explore.fast.design/components/fast-text-field
Ionic ion-input element: https://ionicframework.com/docs/api/input
Polymer paper-input element: https://www.webcomponents.org/element/@polymer/paper-input
and many more...
Regardless of the lib choice an application takes, what is needed in common is the ability to have a concise syntax to describe the two way binding intention with those custom elements. Some examples for the above custom input elements:
<fast-text-field value.bind="message">
<ion-input value.bind="message">
<paper-input value.bind="message">should be treated as:
<fast-text-field value.two-way="message">
<ion-input value.two-way="message">
<paper-input value.two-way="message">In the next section, we will look into how to teach Aurelia such knowledge.
As mentioned earlier, the Attribute Syntax Mapper will be used to map value.bind into value.two-way. Every Aurelia application uses a single instance of this class. The instance can be retrieved via the injection of interface IAttrMapper, like the following example:
import { inject, IAttrMapper } from '@aurelia/runtime-html';
@inject(IAttrMapper)
export class MyCustomElement {
constructor(attrMapper) {
// do something with the attr mapper
}
}After grabbing the IAttrMapper instance, we can use the method useTwoWay(fn) of it to extend its knowledge. Following is an example of teaching it that the bind command on value property of the custom input elements above should be mapped to two-way:
attrMapper.useTwoWay(function(element, property) {
switch (element.tagName) {
// <fast-text-field value.bind="message">
case 'FAST-TEXT-FIELD': return property === 'value';
// <ion-input value.bind="message">
case 'ION-INPUT': return property === 'value';
// <paper-input value.bind="message">
case 'PAPER-INPUT': return property === 'value';
// let other two way mapper check the validity
default:
return false;
}
})Teaching Aurelia to map value.bind to value.two-way is the first half of the story. The second half is about how we can teach Aurelia to observe the value property for changes on those custom input elements. We can do this via the Node Observer Locator. Every Aurelia application uses a single instance of this class, and this instance can be retrieved via the injection of interface INodeObserverLocator like the following example:
import { inject, INodeObserverLocator } from '@aurelia/runtime-html';
@inject(INodeObserverLocator)
export class MyCustomElement {
constructor(nodeObserverLocator) {
// do something with the locator
}
}After grabbing the INodeObserverLocator instance, we can use the method useConfig of it to extend its knowledge. Following is an example of teaching it that the value property, on a <fast-text-field> element could be observed using change event:
nodeObserverLocator.useConfig('FAST-TEXT-FIELD', 'value', { events: ['change' ] });Similarly, examples for <ion-input> and <paper-input>:
nodeObserverLocator.useConfig('ION-INPUT', 'value', { events: ['change' ] });
nodeObserverLocator.useConfig('PAPER-INPUT', 'value', { events: ['change' ] });If an object is passed to the .useConfig API of the Node Observer Locator, it will be used as a multi-registration call, as per following example, where we register <fast-text-field>, <ion-input>, <paper-input> all in a single call:
nodeObserverLocator.useConfig({
'FAST-TEXT-FIELD': {
value: { events: ['change'] }
},
'ION-INPUT': {
value: { events: ['change'] }
},
'PAPER-INPUT': {
value: { events: ['changer'] }
}
})Combining the examples in the two sections above into some more complete code block example, for Microsoft FAST components:
import { inject, IContainer, IAttrMapper, INodeObserverLocator, AppTask, Aurelia } from 'aurelia';
Aurelia
.register(
AppTask.creating(IContainer, container => {
const attrMapper = container.get(IAttrMapper);
const nodeObserverLocator = container.get(INodeObserverLocator);
attrMapper.useTwoWay((el, property) => {
switch (el.tagName) {
case 'FAST-TEXT-FIELD': return property === 'value';
case 'FAST-TEXT-AREA': return property === 'value';
case 'FAST-SLIDER': return property === 'value';
// etc...
}
});
nodeObserverLocator.useConfig({
'FAST-TEXT-FIELD': {
value: { events: ['change'] }
},
'FAST-TEXT-AREA': {
value: { events: ['change'] }
},
'FAST-SLIDER': {
value: { events: ['change'] }
}
});
})
)
.app(class MyApp {})
.start();And with the above, your Aurelia application will get two way binding flow seamlessly:
<fast-text-field value.bind="message"></fast-text-field>
<fast-text-area value.bind="description"></fast-text-area>
<fast-slider value.bind="fontSize"></fast-slider>Aurelia provides a higher-level API for simplifying some common tasks to handle a common reactivity intent in any application: run a function again when any of its dependencies have been changed.
This function is called an effect, and the dependencies are typically tracked when they are accessed (read) inside this effect function. The builtin @observable decorator from Aurelia enables this track-on-read capability by default.
Aurelia provides a few ways to declare a dependency for an effect function. The most common one is the track "on read" of a reactive property.
In the following example:
class MouseTracker {
@observable
coord = [0, 0];
}The property coord of a MouseTracker instance will be turned into a reactive property and is also aware of effect function dependency tracking.
The effect APIs are provided via the default implementation of the interface IObservation, which can be retrieved like one of the following examples:
Getting from a container directly:
import { IObservation } from 'aurelia';
...
const observation = someContainer.get(IObservation);Getting through injection:
import { inject, IObservation } from 'aurelia';
@inject(IObservation)
class MyElement {
constructor(observation) {
// ...
}
}Or
class MyElement {
constructor(@IObservation readonly observation) {
// ...
}
}After getting the observation object, there are two APIs that can be used to created effects as described in the following sections:
Watch effect is a way to describe a getter based observation of an object. An example to create watch effect is per the following:
import { inject, IObservation } from 'aurelia';
@inject(IObservation)
class PersonalInfo {
constructor(observation) {
const effect = observation.watch(this.primaryInfo, (primaryInfo) => primaryInfo.name, function nameChanged(newName, oldName) {
// do something with name
});
// effect.stop() later when necessary
}
}Note that the effect function will be run immediately. If you do not want to run the callback immediately, pass an option immediate: false as the 4th parameter:
observation.watch(obj, getter, callback, { immediate: false });By default, a watch effect is independent of any application lifecycle, which means it does not stop when the application that owns the observation instance has stopped. To stop/destroy an effect, call the method stop() on the effect object.
Run effects describe a function to be called repeatedly whenever any dependency tracked inside it changes.
After getting an IObservation instance, a run effect can be created via the method run of it:
const effect = observation.run(() => {
// code here
});Note that the effect function will be run immediately.
By default, a effect is independent of any application lifecycle, which means it does not stop when the application that owns the observation instance has stopped. To stop/destroy an effect, call the method stop() on the effect object:
const effect = IObservation.run(() => {
// code here
});
// stop the effect like this
effect.stop();The following section gives some examples of what it looks like when combining @observable and run effect.
import { inject, IObservation, observable } from 'aurelia'
class MouseTracker {
@observable coord = [0, 0]; // x: 0, y: 0 is the default value
}
// Inside an application:
@inject(IObservation)
class App {
constructor(observation) {
const mouseTracker = new MouseTracker();
document.addEventListener('mousemove', (e) => {
mouseTracker.coord = [e.pageX, e.pageY]
});
observation.run(() => {
console.log(mouseTracker.coord)
});
}
}Now whenever the user moves the mouse around, a log will be added to the console with the coordinate of the mouse.
import { inject, IObservation, observable } from 'aurelia'
class PageActivity {
@observable active = false
}
// Inside an application:
@inject(IObservation)
class App {
constructor(observation) {
const pageActivity = new PageActivity();
document.addEventListener(visibilityChange, (e) => {
pageActivity.active = !document.hidden;
});
observation.run(() => {
fetch('my-game/user-activity', { body: JSON.stringify({ active: pageActivity.active }) })
});
}
}How to implement router "guards" into your applications to protect routes from direct access.
You might know router hooks as guards in other routers. Their role is to determine how components are loaded. They're pieces of code that are run in between.
The lifecycle hooks sharing API can be used to define reusable hook logic. In principle, nothing new needs to be learned: their behavior is the same as described in Lifecycle Hooks, with the only difference being that the view model instance is added as the first parameter.
If you worked with Aurelia 1, you might know these by their previous name: router pipelines.
import Aurelia, { lifecycleHooks } from 'aurelia';
import { Parameters, Navigation, RouterConfiguration, RoutingInstruction } from '@aurelia/router';
@lifecycleHooks()
class NoopAuthHandler {
canLoad(viewModel, params: Parameters, instruction: RoutingInstruction, navigation: Navigation) {
return true;
}
}
Aurelia
.register(RouterConfiguration, NoopAuthHandler)
.app(component)
.start();Shared lifecycle hook logic can be defined by implementing a router lifecycle hook on a class with the @lifecycleHooks() decorator. This hook will be invoked for each component where this class is available as a dependency. This can be either via a global registration or via one or more component-local registrations, similar to how, e.g. custom elements and value converters are registered.
In the example above, we register NoopAuthHandler globally, which means it will be invoked for each routed component and return true each time, effectively changing nothing.
Because lifecycle hooks are invoked for each component, it is considered best practice to ensure that you name your lifecycle hooks appropriately, especially if you're working in a team where developers might not be aware of hooks modifying global component lifecycle behaviors.
While lifecycle hooks are indeed their own thing independent of the components you are routing to, the functions are basically the same as you would use inside an ordinary component.
This is the contract for ordinary route lifecycle hooks for components:
import { Parameters, IRouteableComponent, Navigation, RoutingInstruction } from '@aurelia/router';
class MyComponent implements IRouteableComponent {
canLoad(params: Parameters, instruction: RoutingInstruction, navigation: Navigation);
loading(params: Params, instruction: RoutingInstruction, navigation: Navigation);
canUnload(instruction: RoutingInstruction, navigation: Navigation);
unloading(instruction: RoutingInstruction, navigation: Navigation);
}And this is the contract for shared lifecycle hooks
import { lifecycleHooks } from 'aurelia';
import { Parameters, Navigation, RoutingInstruction } from '@aurelia/router';
@lifecycleHooks()
class MySharedHooks {
canLoad(viewModel, params: Parameters, instruction: RoutingInstruction, navigation: Navigation);
loading(viewModel, params: Params, instruction: RoutingInstruction, navigation: Navigation);
canUnload(viewModel, instruction: RoutingInstruction, navigation: Navigation);
unloading(viewModel, instruction: RoutingInstruction, navigation: Navigation);
unload(viewModel, instruction: RoutingInstruction, navigation: Navigation);
}The only difference is the addition of the first viewModel parameter. This comes in handy when you need the component instance since the this keyword won't give you access like in ordinary component methods.
When dealing with route hooks, you might only want to apply those to specific components. Imagine an authentication workflow where you would want to allow unauthenticated users to access your login or contact page.
To do this, we can specify our route hook as a dependency in the component via the static dependencies property, which takes an array of one or more dependencies.
import { IRouteableComponent } from "@aurelia/router";
import { AuthHook } from './route-hook';
export class SettingsPage implements IRouteableComponent {
static dependencies = [ AuthHook ];
}Whenever someone tries to route to the SettingsPage component, they will trigger the authentication hook you created. This per-component approach allows you to target the needed components you want behind a route hook.
Shared lifecycle hooks run in parallel with (but are started before) component instance hooks, and multiple of the same kind can be applied per component. When multiple hooks are registered per component, they are invoked in the registration order.
import { lifecycleHooks } from 'aurelia';
@lifecycleHooks()
class Log1 {
async loading() {
console.log('1.start');
await Promise.resolve();
console.log('1.end');
}
}
@lifecycleHooks()
class Log2 {
async loading() {
console.log('2.start');
await Promise.resolve();
console.log('2.end');
}
}
export class MyComponent {
static dependencies = [Log1, Log2];
async loading() {
console.log('3.start');
await Promise.resolve();
console.log('3.end');
}
}
// Will log, in order:
// 1.start
// 2.start
// 3.start
// 1.end
// 2.end
// 3.endIt is also permitted to define more than one hook per shared hook class:
@lifecycleHooks()
export class LifecycleLogger {
canLoad(viewModel, params, instruction, navigation) {
console.log(`invoking canLoad on ${instruction.component.name}`);
return true;
}
loading(viewModel, params, instruction, navigation) {
console.log(`invoking load on ${instruction.component.name}`);
}
}Every component instance has a lifecycle that you can tap into. This makes it easy for you to perform various actions at particular times.
For example, you may want to execute some code as soon as your component properties are bound but before the component is first rendered. Or, you may want to run some code to manipulate the DOM as soon as possible after your element is attached to the document.
If you register a listener or subscriber in one callback, remember to remove it in the opposite callback. For example, a native event listener registered in attached should be removed in detached
When the framework instantiates a component, it calls your class's constructor, just like any JavaScript class. This is the best place to put your basic initialization code that is not dependent on bindable properties.
Furthermore, the constructor is where you handle the injection of dependencies using dependency injection. You will learn about DI in the dependency injection section, but here is a basic example of where the constructor is used.
import { IRouter } from '@aurelia/router-lite';
export class MyComponent {
constructor(@IRouter readonly router: IRouter) {
}
}The "hydrating" hook allows you to add contextual DI registrations (to controller.container) to influence which resources are resolved when the template is compiled. It is still considered part of "construction".
export class MyComponent {
hydrating(controller: IContextualCustomElementController<this>) {
}
}The "hydrated" hook is a good place to influence how child components are constructed and rendered contextually. It runs synchronously after the definition is compiled (which happens synchronously after hydrating) and, like hydrating, can still be considered part of "construction".
export class MyComponent {
hydrated(controller: IContextualCustomElementController<this>) {
}
}The "created" hook is the last hook that can be considered part of "construction". It is called (synchronously) after this component is hydrated, which includes resolving, compiling and hydrating child components. In terms of the component hierarchy, the created hooks execute bottom-up, from child to parent (whereas hydrating and hydrated are all top-down). This is also the last hook that runs only once per instance.
Here you can perform any last-minute work that requires having all child components hydrated, which might affect the bind and attach lifecycles.
export class MyComponent {
created(controller: IContextualCustomElementController<this>) {
}
}If your component has a method named "binding", then the framework will invoke it after the bindable properties of your component are assigned. In terms of the component hierarchy, the binding hooks execute top-down, from parent to child, so your bindables will have their values set by the owning components, but the bindings in your view are not yet set.
You can optionally return a Promise either making the method asynchronous or creating a promise object. If you do so, it will suspend the binding and attaching of the children until the promise is resolved. This is useful for fetching/save of data before rendering.
export class MyComponent {
binding(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "bound", then the framework will invoke it when the bindings between your component and its view have been set. This is the best place to do anything that requires the values from let, from-view or ref bindings to be set.
export class MyComponent {
bound(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "attaching, " the framework will invoke it when it has attached the component's HTML element. You can queue animations and/or initialize certain 3rd party libraries.
export class MyComponent {
attaching(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "attached", the framework will invoke it when it has attached the current component and all of its children. In terms of the component hierarchy, the attached hooks execute bottom-up.
export class MyComponent {
attached(initiator: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "detaching", then the framework will invoke it when removing your HTML element from the document. In terms of the component hierarchy, the detaching hooks execute bottom-up.
export class MyComponent {
detaching(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "unbinding, " the framework will invoke it when it has fully removed your HTML element from the document. In terms of the component hierarchy, the unbinding hooks execute bottom-up.
export class MyComponent {
unbinding(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags) {
}
}If your component has a method named "dispose", then the framework will invoke it when the component is to be cleared from memory completely. It may be called, for example, when a component is in a repeater, and some items are removed that are not returned to the cache.
This is an advanced hook mostly useful for cleaning up resources and references that might cause memory leaks if never explicitly dereferenced.
export class MyComponent {
dispose() {
}
}The lifecycle hooks API supports all of the above lifecycle methods. Using the lifecycleHooks decorator, you can perform actions at various points of the component lifecycle. Because the router uses lifecycle hooks, they are documented here in the router section, but do not require the use of the router to use (except for router-specific hooks).
For <au-compose>, there are extra lifecycle hooks that are activate/deactivate. Refers to dynamic composition doc for more details.
Testing components in Aurelia 2 is a straightforward process thanks to the framework's design and the utilities provided by the @aurelia/testing package. This guide will walk you through the steps to test your components effectively, ensuring they work as expected within the context of a view.
In Aurelia, a component typically consists of a view (HTML) and a view model (JavaScript or TypeScript). To ensure the quality and correctness of your components, you should write tests that cover both aspects. Testing components involves checking that the view renders correctly with given data and that the view model behaves as intended when interacting with the view.
When testing components, we will focus on integration tests that involve both the view and view model. This approach allows us to verify the component as a whole, as it would function within an Aurelia application.
For demonstration purposes, we will use a simple PersonDetail component with bindable properties name and age.
import { bindable } from 'aurelia';
export class PersonDetail {
@bindable name: string;
@bindable age: number;
}<template>
<p>Person is called ${name} and is ${age} years old.</p>
</template>We aim to test that the PersonDetail component renders the expected text when provided with name and age properties.
Before writing the test, ensure your environment is correctly set up for testing. Refer to the Overview section for details on how to initialize the Aurelia testing platform.
Create a test file for your component, such as person-detail.spec.ts, and implement your tests using the syntax of your chosen test runner. The following example uses Jest:
import { createFixture } from '@aurelia/testing';
import { PersonDetail } from './person-detail';
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';
describe('PersonDetail component', () => {
beforeAll(() => {
// Initialize the test environment before running the tests
bootstrapTestEnvironment();
});
it('renders the name and age correctly', async () => {
const { component, startPromise, tearDown } = createFixture(
'<person-detail name.bind="testName" age.bind="testAge"></person-detail>',
class App {
testName = 'Alice';
testAge = 30;
},
[PersonDetail]
);
await startPromise;
expect(component.textContent).toContain('Person is called Alice and is 30 years old.');
await tearDown();
});
// Additional tests...
});In this example, createFixture is used to instantiate the component with a test context, binding name and age to specified values. We then assert that the component's text content includes the correct information. After the test completes, tearDown cleans up the component instance to avoid memory leaks and ensure test isolation.
If your component has dependencies, such as services or other custom elements, you'll need to register these within the Aurelia testing container.
Assume PersonDetail depends on a PersonFormatter service:
import { inject } from 'aurelia';
import { PersonFormatter } from './person-formatter';
@inject(PersonFormatter)
export class PersonDetail {
@bindable name: string;
@bindable age: number;
constructor(private personFormatter: PersonFormatter) {}
get formattedDetails() {
return this.personFormatter.format(this.name, this.age);
}
}To test this component, you can create a mock PersonFormatter and register it with the Aurelia container:
import { createFixture, Registration } from '@aurelia/testing';
import { PersonDetail } from './person-detail';
import { PersonFormatter } from './person-formatter';
describe('PersonDetail with PersonFormatter dependency', () => {
it('formats the details using PersonFormatter', async () => {
const mockPersonFormatter = {
format: jest.fn().mockImplementation((name, age) => `Formatted: ${name}, age ${age}`),
};
const { component, startPromise, tearDown } = createFixture(
'<person-detail name.bind="testName" age.bind="testAge"></person-detail>',
class App {
testName = 'Bob';
testAge = 40;
},
[PersonDetail],
[Registration.instance(PersonFormatter, mockPersonFormatter)]
);
await startPromise;
expect(mockPersonFormatter.format).toHaveBeenCalledWith('Bob', 40);
expect(component.textContent).toContain('Formatted: Bob, age 40');
await tearDown();
});
});In the test above, we use Jest's jest.fn() to create a mock implementation of PersonFormatter. We then verify that the mock's format method is called with the correct arguments and that the component's text content includes the formatted details.
Testing Aurelia components involves setting up a test environment, creating fixtures, and writing assertions based on your expectations. By following these steps and best practices, you can ensure that your components are reliable and maintainable. Remember to clean up after your tests to maintain a clean test environment and to avoid any side effects between tests.
Template references in Aurelia 2 provide a powerful and flexible way to connect your HTML templates with your JavaScript or TypeScript view models. Using the ref attribute, you can easily identify and interact with specific parts of your template, making it more efficient to manipulate the DOM or access template data.
Add the ref attribute to an HTML element within your template to create a template reference. This marks the element as a reference, allowing you to access it directly in your view model.
<input type="text" ref="myInput" placeholder="First name">In this example, myInput references the input element, which can be used both in the template and the corresponding view model.
Template references are immediately available within the template. For instance, you can display the value of the input field as follows:
<p>${myInput.value}</p>This binding displays the current value of the input field dynamically.
To access the referenced element in the view model, declare a property with the same name as the reference. For TypeScript users, it's important to define the type of this property for type safety.
export class MyApp {
private myInput: HTMLInputElement;
// Additional view model logic here
}Aurelia's ref attribute is not limited to standard HTML elements. It can also be used with custom elements and attributes to reference their component instances (view-models) or controllers.
Custom Element Instance Use component.ref="expression" to create a reference to a custom element's component instance (view-model). This was known as view-model.ref in Aurelia v1.
<my-custom-element component.ref="customElementVm"></my-custom-element>Custom Attribute Instance Similarly, custom-attribute.ref="expression" can reference a custom attribute's component instance (view-model).
<div my-custom-attribute custom-attribute.ref="customAttrVm"></div>Controller Instance For more advanced scenarios, controller.ref="expression" creates a reference to a custom element's controller instance.
<my-custom-element controller.ref="customElementController"></my-custom-element>Template references are incredibly useful for integrating with third-party libraries or when direct DOM manipulation is necessary. Instead of using traditional JavaScript queries to find elements, template references provide a more straightforward, framework-integrated approach.
interface INavigationModel {
/**
* Collection of routes.
*/
readonly routes: readonly {
readonly id: string;
readonly path: string[];
readonly redirectTo: string | null;
readonly title: string | ((node: RouteNode) => string | null) | null;
readonly data: Record<string, unknown>;
readonly isActive: boolean;
}[];
}import { INavigationModel, IRouteContext } from '@aurelia/router-lite';
export class NavBar {
private readonly navModel: INavigationModel;
public constructor(@IRouteContext routeCtx: IRouteContext) {
this.navModel = routeCtx.navigationModel;
}
public async binding() {
await this.navModel.resolve()
}
}<nav style="display: flex; gap: 0.5rem;">
<template repeat.for="route of navModel.routes">
<a href.bind="route.path | firstNonEmpty">\${route.title}</a>
</template>
</nav><style>
.active {
font-weight: bold;
}
</style>
<nav>
<template repeat.for="route of navModel.routes">
<a href.bind="route.path | firstNonEmpty" active.class="route.isActive">${route.title}</a>
</template>
</nav>import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
import { NotFound } from './not-found';
@route({
routes: [
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: 'about',
component: About,
title: 'About',
},
{
path: 'notfound',
component: NotFound,
title: 'Not found',
nav: false, // <-- exclude from navigation model
},
],
fallback: 'notfound',
})
export class MyApp {}Learn about binding values to attributes of DOM elements and how to extend the attribute mapping with great ease.
When dealing with Aurelia and custom elements, we tend to use the @bindable decorator to define bindable properties. The bindable properties are members of the underlying view model class. However, there are cases where we want to work directly with attributes of the DOM elements.
For example, we want an <input> element with a maxlength attribute and map a view model property to the attribute. Let us assume that we have the following view model class:
export class App {
private inputMaxLength: number = 10;
private input: HTMLInputElement;
}Then, intuitively, we would write the following template:
<input maxlength.bind="inputMaxLength" ref="input">This binds the value to the maxlength attribute of the <input> element. Consequently, the input.maxLength is also bound to be 10. Note that binding the value of the maxLength attribute also sets the value of the maxLength property of the input element. This happens because Aurelia, in the background, does the mapping for us.
On a broad level, this is what attribute mapping is about. This article provides further information about how it works and how to extend it.
To facilitate the attribute mapping, Aurelia uses IAttrMapper, which has information about how to map an attribute to a property. While creating property binding instructions from binding commands, it is first checked if the attribute is a bindable. If it is a bindable property, the attribute name (in kebab-case) is converted to the camelCase property name. However, the attribute mapper is queried for the target property name when it is not a bindable. If the attribute mapper returns a property name, then the property binding instruction is created with that property name. Otherwise, the standard camelCase conversion is applied.
If we want to bind a non-standard <input> attribute, such as fizz-buzz, we can expect the input.fizzBuzz property to be bound. This looks as follows.
<input fizz-buzz.bind="someValue" ref="input">export class App {
private someValue: number = 10;
private input: HTMLInputElement;
public attached(): void {
console.log(this.input.fizzBuzz); // 10
}
}The attribute mapping can be extended by registering new mappings with the IAttrMapper. The IAttrMapper provides two methods for this purpose. The .useGlobalMapping method registers mappings applicable for all elements, whereas the .useMapping method registers mapping for individual elements.
To this end, we can grab the IAttrMapper instance while bootstrapping the app and register the mappings (there is no restriction, however, on when or where those mappings are registered). An example might look as follows.
import {
AppTask,
Aurelia,
IAttrMapper,
} from '@aurelia/runtime-html';
const au = new Aurelia();
au.register(
AppTask.creating(IAttrMapper, (attrMapper) => {
attrMapper.useMapping({
'MY-CE': {
'fizz-buzz': 'FizzBuzz',
},
INPUT: {
'fizz-buzz': 'fizzbuzz',
},
});
attrMapper.useGlobalMapping({
'foo-bar': 'FooBar',
});
})
);In the example above, we are registering a global mapping for foo-bar attribute to FooBar property, which will apply to all elements. We are also registering mappings for individual elements. Note that the key of the object is the nodeName of the element; thus, for an element, it needs to be the element name in upper case. In the example above, we map the fizz-buzz attribute differently for <input> and <my-ce> elements.
With this custom mapping registered, we can expect the following to work.
<input fizz-buzz.bind="42" foo-bar.bind="43" ref="input">
<my-ce fizz-buzz.bind="44" foo-bar.bind="45" ref="myCe"></my-ce>export class App {
private input: HTMLInputElement;
private myCe: HTMLElement;
public attached(): void {
console.log(this.input.fizzbuzz); // 42
console.log(this.input.FooBar); // 43
console.log(this.myCe.FizzBuzz); // 44
console.log(this.myCe.FooBar); // 45
}
}In addition to registering custom mappings, we can teach the attribute mapper when using two-way binding for an attribute. To this end, we can use the .useTwoWay method of the IAttrMapper. The .useTwoWay method accepts a predicate function determining whether the attribute should be bound in two-way mode. The predicate function receives the attribute name and the element name as parameters. If the predicate function returns true, then the attribute is bound in two-way mode, otherwise it is bound in to-view mode.
An example looks as follows.
import {
AppTask,
Aurelia,
IAttrMapper,
} from '@aurelia/runtime-html';
const au = new Aurelia();
au.register(
AppTask.creating(IAttrMapper, (attrMapper) => {
// code omitted for brevity
attrMapper.useTwoWay(
(el, attr) => el.tagName === 'MY-CE' && attr == 'fizz-buzz'
);
})
);In this example, we are instructing the attribute mapper to use two-way binding for fizz-buzz attribute of <my-ce> element. This means that the following will work.
<my-ce
ref="myCe"
foo-bar.bind="myCeFooBar"
fizz-buzz.bind="myCeFizzBuzz"></my-ce>
myCeFizzBuzz: ${myCeFizzBuzz} myCeFooBar: ${myCeFooBar}export class MyApp {
private myCeFooBar: any = 'fizz';
private myCeFizzBuzz: any = '2424';
private myCe: HTMLElement & { FooBar?: string; FizzBuzz?: string };
public attached() {
setInterval(() => {
// This change will trigger a change for the myCeFizzBuzz property
this.myCe.FizzBuzz = Math.ceil(Math.random() * 10_000).toString();
// This change won't trigger a change for the myCeFooBar property
this.myCe.FooBar = Math.ceil(Math.random() * 10_000).toString();
}, 1000);
}
}A similar example can be seen in action below.
Routing with Aurelia feels like a natural part of the framework. It can easily be implemented into your applications in a way that feels familiar if you have worked with other frameworks and library routers. Here is a basic example of routing in an Aurelia application using router-lite.
The following getting started guide assumes you have an Aurelia application already created. If not, consult our Quick Start to get Aurelia installed in minutes.
npm i @aurelia/router-literouter-liteTo use the router-lite, we have to register it with Aurelia. We do this at the bootstrapping phase.
import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router-lite';
import { MyApp } from './my-app';
Aurelia
.register(RouterConfiguration.customize({
useUrlFragmentHash: true, // <-- enables the routing using the URL `hash`
}))
.app(MyApp)
.start();For this example, we have a root component which is MyApp. And then we are going to define two routes for the root component, namely home and about.
Let us define these components first.
import { customElement } from '@aurelia/runtime-html';
import template from './home.html';
@customElement({ name: 'ho-me', template })
export class Home {
private readonly message: string = 'Welcome to Aurelia2 router-lite!';
}<h1>${message}</h1>import { customElement } from '@aurelia/runtime-html';
import template from './about.html';
@customElement({ name: 'ab-out', template })
export class About {
private readonly message = 'Aurelia2 router-lite is simple';
}<h1>${message}</h1>With the routable components in place, let's define the routes. To this end, we need to add the route configurations to our root component MyApp.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
import { Home } from './home';
import { About } from './about';
@route({
routes: [
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: 'about',
component: About,
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}
<nav>
<a href="home">Home</a>
<a href="about">About</a>
</nav>
<au-viewport></au-viewport>There are couple of stuffs to note here. We start by looking at the configurations defined using the @route decorator where we list out the routes under the routes property in the configuration object in the @route decorator. The most important things in every route configurations are the path and the component properties. This instructs the router to use the defined component in the viewport when it sees the associated path.
The viewport is specified in the view (see my-app.html) by using the <au-viewport> custom element. For example, the router will use this element to display the Home component when it sees the / (the empty path) or the /home paths.
The nav>a elements are added to navigate from one view to another.
See this in action:
If you have opened the demo then you can notice that the URL in the address bar or the URLs in the nav>a elements contains a # (example: /#home, /#about etc.). Depending on your project need and esthetics you may want to get rid of the #-character. To this end, you need set the useUrlFragmentHash to false, which is also the default.
For the documentation of router-lite, many live examples are prepared. It is recommended to use the live examples as you read along the documentation. However, if you are feeling adventurous enough to explore the features by yourself, here is the complete collection of the live examples at your disposal.
Remove boilerplate from your applications with template lambda expressions.
Lambda expressions in Aurelia templates offer a concise and powerful way to include JavaScript-like functionality directly within your HTML using a subset of Arrow Function syntax. This feature enhances the expressiveness of Aurelia's templating engine, allowing for more inline, readable, and maintainable code.
One of the most common scenarios will likely be calling Array methods on an array you're looping over using repeat.for.
Previously, to filter some array items in a repeater, you might have written something like this using a value converter:
While there is nothing wrong with value converters, and in some situations, they might be preferable (especially for testing), you can achieve the same thing without writing any additional code like this:
We are calling a callback function called isGood defined inside our template to determine if the item is filtered.
Observation-wise, Aurelia knows only to observe selected property of every item in items, as well as pos property of every selected item. This means changing the value of selected property of any item will result in the re-evaluation of the above expression. Changing the value of pos property of any selected item will also trigger the re-evaluation. Aurelia will also subscribe to the mutation of the array items to refresh this binding.
As we might have inside of a value converter, we use two Javascript functions, filter and sort — Aurelia's lambda expression support means we can chain these functions without needing to write any code in a view-model or value converter.
With arrow functions, we can express the following:
As the following:
As a result, .call is being deprecated in Aurelia as the lambda expression syntax allows us to handle this in a more JavaScript way.
Not only are lambda functions supported in a repeat.for, but we can also use them in interpolation expressions.
Say you have an array of keywords for an item, and you want to display those as a comma-separated list. Previously, you would have used a value converter or function in your view model to achieve this task. Now, you can do it from within your templates.
Another task might be to take an array of items (say, products in a cart) and then calculate the total. Once again, we might have previously used a value converter or computed getter for this task, but now we can use reduce in our template.
While a broad syntax for lambda expressions is supported, here is a list of valid uses.
The following uses of lambda expressions are not supported in Aurelia templates.
Now we understand what lambda expressions are and how they can be used, here are some examples of how you might leverage them in your Aurelia applications.
Transform and display an array of objects inline, such as a list of names.
Use lambda expressions for complex filtering, such as filtering based on multiple object properties.
Handle events with additional context passed to the event handler.
Perform operations on nested arrays, such as displaying a flattened list of sub-items.
Chain multiple array methods for data processing.
Calculate the total price of items in a shopping cart.
Transform an array of objects into a comma-separated list.
Use reduce to calculate an aggregate property, such as the average age.
includes for Conditional RenderingCheck if an array includes a certain value and conditionally render content.
includesAssign a class to an element if an array includes a specific item.
findDisplay details of the first item that matches a condition.
find in Event HandlingUse find in an event handling expression to work with a specific item.
flatFlatten a nested array and display its contents.
Use flat to create a flattened list of attributes from an array of objects.
Local templates allow you to remove boilerplate in your Aurelia applications, by creating local templates specific to the templated view you are working within and are not reusable.
In many instances, when working with templated views in Aurelia, you will be approaching development from a reusability mindset. However, sometimes, you need a template for one specific application part. You could create a component for this, but it might be overkill. This is where local templates can be useful.
The example defines a template inside the my-app.html markup that can be used as a custom element. The name of the custom element, so defined, comes from the value of the as-custom-element attribute used on the template.
In this case, it is named as person-info. A custom element defined that way cannot be used outside the template that defines it; in this case, the person-info is, therefore, unavailable outside my-app. Thus, the name 'local template'.
Local templates can also optionally specify bindable properties using the <bindable> tag as shown above. Apart from property, other allowed attributes that can be used in this tag are attribute, and mode. In that respect, the following two declarations are synonymous.
Although it might be quite clear, it is worth reiterating that the value of the bindable attribute should not be camelCased or PascalCased.
In essence, the local templates are similar to HTML-Only custom elements, with the difference that the local templates cannot be reused outside the defining custom element. Sometimes we need to reuse a template multiple times in a single custom element.
Creating a separate custom element for that is a bit overkill. Also, given that the custom element is only used in one single custom element, it might be optimized for that and not meant to be reused outside this context. The local templates are meant to promote that, whereas having a separate custom element makes it open for reuse in another context.
In short, it aims to reduce boilerplate code and promotes highly cohesive, better-encapsulated custom elements.
This means that the following is a perfectly valid example. Note that the local templates with the same name (foo-bar) are defined in different custom elements.
Like anything, there is always an upside and downside: local templates are no different. While they can be a powerful addition to your Aurelia applications, you need to be aware of the caveats when using them, as you may encounter them.
It is theoretically possible to go to an infinite level of nesting. That is, the following example will work. However, whether such composition is helpful depends on the use case.
Although it might provide a stronger cohesion, as the level of nesting grows, it might not be easy to work with. It is up to you to decide on a reasonable tradeoff while using local templates.
In this respect, a good thumb rule is to keep the local function analogy in mind.
The following examples will cause a (jit) compilation error.
The following example will cause a (jit) compilation error.
The following example will cause a (jit) compilation error.
The following example will cause a (jit) compilation error.
The following example will cause a (jit) compilation error.
The following example will cause a (jit) compilation error.
Learn how to manipulate the DOM from the usage-side of a custom element using the processContent hook.
There are scenarios where we would like to transform the template provided by the usage-side. The 'processContent' hook lets us define a pre-compilation hook to make that transformation.
The signature of the hook function is as follows.
There are two important things to note here.
First is the node argument. It is the DOM tree on the usage-side for the custom element. For example, if there is a custom element named my-element, on which a 'processContent' hook is defined, and it is used somewhere as shown in the following markup, then when the hook is invoked, the node argument will provide the DOM tree that represents the following markup.
Then inside the hook this DOM tree can be transformed/mutated into a different DOM tree. The mutation can be addition/removal of attributes or element nodes.
Second is the return type boolean | void. Returning from this function is optional. Only an explicit false return value results in skipping the compilation (and thereby enhancing) of the child nodes in the DOM tree. The implication of skipping the compilation of the child nodes is that Aurelia will not touch those DOM fragments and will be kept as it is. In other words, if the mutated node contains custom elements, custom attributes, or template controllers, those will not be hydrated.
The platform argument is just the helper to have platform-agnostic operations as it abstracts the platform. Lastly the this argument signifies that the hook function always gets bound to the custom element class function for which the hook is defined.
The most straight forward way to define the hook is to use the processContent property while defining the custom-element.
Apart from this, there is also the @processContent decorator which can used class-level or method-level.
That's the API. Now let us say consider an example. Let us say that we want to create a custom elements that behaves as a tabs control. That is this custom element shows different sets of information grouped under a set of headers, and when the header is clicked the associated content is shown. To this end, we can conceptualize the markup for this custom element as follows.
The markup has 2 slots for the header and content projection. While using the tabs custom element we want to have the following markup.
Now note that there is no custom element named tab. The idea is to keep the usage-markup as much dev-friendly as possible, so that it is easy to maintain, and the semantics are quite clear. Also it is easy to refactor as now we know which parts belong together. To support this usage-syntax we will use the 'processContent' hook to rearrange the DOM tree, so that the nodes are correctly projected at the end. A prototype implementation is shown below.
Example transformation function for default [au-slot]
If you have used , you might have noticed that in order to provide a projection the usage of [au-slot] attribute is mandatory, even if the projections are targeted to the default au-slot. With the help of the 'processContent' hook we can workaround this minor inconvenience. The following is a sample transformation function that loops over the direct children under node and demotes the nodes without any [au-slot] attribute to a synthetic template[au-slot] node.
The CustomElement resource is a core concept in Aurelia 2, enabling developers to create encapsulated and reusable components. Understanding how to leverage the CustomElement API is crucial for building robust applications. In this documentation, we will delve into the usage of CustomElement and its methods, providing detailed examples and explanations.
This method retrieves the Aurelia controller associated with a DOM node. The controller offers access to the element's view-model, lifecycle, and other properties.
node: The DOM Node for which to retrieve the controller.
opts: An object with optional properties to customize the behavior of the method.
Returns an instance of ICustomElementController or null/undefined, depending on the options provided and whether a controller is found.
The define method registers a class as a custom element in Aurelia.
nameOrDef: A string representing the name or a PartialCustomElementDefinition object with configuration options.
Type: The class containing the logic for the custom element.
Returns a CustomElementType representing the defined custom element.
Retrieves the CustomElementDefinition for a custom element class.
Type: The class of the custom element.
Returns a CustomElementDefinition object with metadata about the custom element.
These methods are used to attach and retrieve metadata to/from a custom element class.
Type: The custom element class to annotate or from which to retrieve annotations.
prop: The property key for the annotation.
value: The value for the annotation (for annotate method).
CustomElement.annotate does not return a value. CustomElement.getAnnotation returns the annotation value.
Generates a unique name for a custom element, which is useful for components that do not require a specific name.
A string representing a unique name for a custom element.
Creates an InjectableToken for dependency injection.
An instance of InjectableToken.
Dynamically generates a CustomElementType with a given name and prototype.
name: The name of the custom element.
proto: An object representing the prototype of the custom element.
A CustomElementType that can be used to define a custom element.
Testing in Aurelia often involves testing components that have dependencies injected into them. Using dependency injection (DI) simplifies the process of replacing these dependencies with mocks, stubs, or spies during testing. This can be particularly useful when you need to isolate the component under test from external concerns like API calls or complex logic.
Mocks are objects that replace real implementations with fake methods and properties that you define. They are useful for simulating complex behavior without relying on the actual implementation.
Stubs are like mocks but typically focus on replacing specific methods or properties rather than entire objects. They are useful when you want to control the behavior of a dependency for a particular test case.
Spies allow you to wrap existing methods so that you can record information about their calls, such as the number of times they were called or the arguments they received.
Sinon is a popular library for creating mocks, stubs, and spies in JavaScript tests. It provides a rich API for controlling your test environment and can significantly simplify the process of testing components with dependencies.
To make use of Sinon in your Aurelia project, you need to install it along with its type definitions for TypeScript support:
If you are not using TypeScript, you can omit the @types/sinon.
After installing Sinon, import it in your test files to access its functionality. Let's look at how to apply Sinon to mock, stub, and spy on dependencies in Aurelia components.
In this example, the MyComponent class has a dependency on IRouter and a method navigate that delegates to the router's load method.
To stub the load method of the router, use Sinon's stub method:
When you need to replace the entire dependency, create a mock object and register it in place of the real one:
By using Registration.instance, we can ensure that any part of the application being tested will receive our mock implementation when asking for the IRouter dependency.
To observe and assert the behavior of methods, use Sinon's spies:
To test that the save method is called correctly, wrap it with a spy:
Unit tests may require you to instantiate classes manually rather than using Aurelia's createFixture. In such cases, you can mock dependencies directly in the constructor:
In this test, we directly provide a mock router object when creating an instance of MyComponent. This technique is useful for more traditional unit testing where you want to test methods in isolation.
Mocking, stubbing, and spying are powerful techniques that can help you write more effective and isolated tests for your Aurelia components. By leveraging tools like Sinon and Aurelia's dependency injection system, you can create test environments that are both flexible and easy to control. Whether you're writing unit tests or integration tests, these methods will enable you to test your components' behavior accurately and with confidence.
Observe changes in your applications.
Aurelia provides a multitude of different wants to observe properties in your components and call a callback function when they change.
The following sections in the observation documentation will help you decide which observation strategy is appropriate for your applications, from the most commonly used to more advanced observation strategies.
The easiest way to watch for changes to specific view model properties is using the @observable decorator which provides an easy way to watch for changes to properties and react accordingly.
While still using the @observable API, the effect observation approach has more boilerplate and is convenient for instances where you want to observe one or more effects. Examples include when the user moves their mouse or other changes you might want to watch, independent of the component lifecycle.
Unlike other forms of observation, HTML observation is when you want to watch for changes to specific properties on elements, especially for web component properties.
The observer locator API allows you to observe properties for changes manually. In many instances, you will want to use @observer or @watch however, the observer locator can be useful in situations where you want to watch the properties of objects.
<div repeat.for="i of list | specialFilterBy"><div repeat.for="i of list.filter(item => isGood(item))"><div repeat.for="item of items.filter(x => x.selected).sort((a, b) => a.pos - b.pos)">
${item.name}
</div><my-input change.call="updateValue($event)">
<my-button click.trigger="handleClick"><my-input change.bind="v => updateValue(v)">
<my-button click.trigger="e => handleClick(e)">${keywords.map(x => x.name).join(', ')})<p>Total: ${items.reduce((sum, product) => sum + product.price, 0)}</p>() => 42(a) => a(...a) => a[0]a => a(a, b) => `${a}${b}`(a, ...rest) => `${a}${rest.join('')}`a => b => a + b() => {} // no function body(a = 42) => a // no default parameters([a]) => a // no destructuring parameters({a}) => a // no destructuring parameters<p>Attendees: ${attendees.map(a => a.name.toUpperCase()).join(', ')}</p><div repeat.for="person of people.filter(p => p.age > 18 && p.city === 'New York')">
${person.name}
</div><button click.trigger="event => deleteItem(event, item.id)">Delete</button><ul>
<li repeat.for="category of categories">
${category.items.flatMap(item => item.subItems).join(', ')}
</li>
</ul><div repeat.for="user of users.filter(u => u.isActive).slice(0, 10).sort((a, b) => a.name.localeCompare(b.name))">
${user.name}
</div><p>Total Price: ${cartItems.reduce((total, item) => total + item.price * item.quantity, 0)}</p><p>Tags: ${article.tags.map(tag => tag.name).join(', ')}</p><p>Average Age: ${users.reduce((total, user, index, array) => total + user.age / array.length, 0).toFixed(2)}</p><div if.bind="users.map(u => u.name).includes('John Doe')">
John Doe is a user.
</div><div repeat.for="product of products" class="${product.tags.includes('sale') ? 'on-sale' : ''}">
${product.name}
</div><div>
Featured Product: ${products.find(p => p.isFeatured).name}
</div><button click.trigger="selectProduct(products.find(p => p.id === selectedProductId))">
Select Product
</button><ul>
<li repeat.for="item of categories.map(c => c.items).flat()">
${item.name}
</li>
</ul><p>Available Colors: ${products.map(p => p.availableColors).flat().join(', ')}</p>import { CustomElement } from 'aurelia';
const myElement = document.querySelector('.my-custom-element');
try {
const controller = CustomElement.for(myElement);
// You can now interact with the custom element's controller
} catch (error) {
console.error('The provided node does not host a custom element.', error);
}const someInnerElement = document.querySelector('.some-inner-element');
const parentController = CustomElement.for(someInnerElement, { searchParents: true });
// parentController is the closest controller up the DOM tree from someInnerElementconst controller = CustomElement.for(myElement, { name: 'my-custom-element' });
if (controller) {
// The controller is for a custom element named 'my-custom-element'
} else {
// No custom element with the specified name found
}const optionalController = CustomElement.for(myElement, { optional: true });
if (optionalController) {
// The node is a custom element and its controller is available
} else {
// The node is not a custom element, no error thrown
}import { CustomElement } from 'aurelia';
@customElement('my-custom-element')
class MyCustomElement {
// Custom element's logic here
}
CustomElement.define('my-custom-element', MyCustomElement);const definition = {
name: 'my-custom-element',
template: '<template><span>${message}</span></template>',
bindables: ['message']
};
CustomElement.define(definition, MyCustomElement);import { CustomElement } from 'aurelia';
const definition = CustomElement.getDefinition(MyCustomElement);
// Access the definition's properties, such as name, template, bindables, etc.CustomElement.annotate(MyCustomElement, 'someProperty', 'someValue');const value = CustomElement.getAnnotation(MyCustomElement, 'someProperty');
// value now holds 'someValue'const uniqueName = CustomElement.generateName();
// Use uniqueName when defining an anonymous custom elementconst myToken = CustomElement.createInjectable();const DynamicElement = CustomElement.generateType('dynamic-element', {
message: 'Hello from Dynamic Element!',
showMessage() {
alert(this.message);
}
});
CustomElement.define('dynamic-element', DynamicElement);npm install sinon @types/sinon -Dimport { IRouter } from '@aurelia/router';
import { customElement } from 'aurelia';
@customElement('my-component')
export class MyComponent {
constructor(@IRouter private router: IRouter) {}
navigate(path: string) {
return this.router.load(path);
}
}import { createFixture } from '@aurelia/testing';
import { MyComponent } from './my-component';
import { IRouter } from '@aurelia/router';
import sinon from 'sinon';
describe('MyComponent', () => {
it('should stub the load method of the router', async () => {
const { startPromise, component, container, tearDown } = createFixture(
`<my-component></my-component>`,
MyComponent,
[]
);
await startPromise;
const router = container.get(IRouter);
const stub = sinon.stub(router, 'load').returnsArg(0);
expect(component.navigate('nowhere')).toBe('nowhere');
stub.restore();
await tearDown();
});
});import { createFixture, Registration } from '@aurelia/testing';
import { MyComponent } from './my-component';
import { IRouter } from '@aurelia/router';
const mockRouter = {
load(path: string) {
return path;
}
};
describe('MyComponent', () => {
it('should use a mock router', async () => {
const { startPromise, component, tearDown } = createFixture(
`<my-component></my-component>`,
MyComponent,
[],
[Registration.instance(IRouter, mockRouter)]
);
await startPromise;
expect(component.navigate('nowhere')).toBe('nowhere');
await tearDown();
});
});import { customElement } from 'aurelia';
@customElement('magic-button')
export class MagicButton {
callbackFunction(event: Event, id: number) {
return this.save(event, id);
}
save(event: Event, id: number) {
// Pretend to call an API or perform some action...
return `${id}__special`;
}
}import { createFixture } from '@aurelia/testing';
import { MagicButton } from './magic-button';
import sinon from 'sinon';
describe('MagicButton', () => {
it('calls save when callbackFunction is invoked', async () => {
const { startPromise, component, tearDown } = createFixture(
`<magic-button></magic-button>`,
MagicButton
);
await startPromise;
const spy = sinon.spy(component, 'save');
component.callbackFunction(new Event('click'), 123);
expect(spy.calledOnceWithExactly(new Event('click'), 123)).toBeTruthy();
spy.restore();
await tearDown();
});
});import { MyComponent } from './my-component';
import { IRouter } from '@aurelia/router';
describe('MyComponent', () => {
const mockRouter: IRouter = {
load(path: string) {
return path;
}
// ... other methods and properties
};
it('should navigate using the mock router', () => {
const component = new MyComponent(mockRouter);
expect(component.navigate('somewhere')).toBe('somewhere');
});
});// pseudo-code; `typeof TCustomElement` doesn't work in Generics form.
<TCustomElement>(this: typeof TCustomElement, node: INode, platform: IPlatform) => boolean | void;<my-element>
<foo></foo>
<bar></bar>
</my-element>import { customElement, INode, IPlatform } from '@aurelia/runtime-html';
// Use a standalone function
function processContent(node: INode, platform: IPlatform) { }
@customElement({ name: 'my-element', processContent })
export class MyElement { }
// ... or use a static method explicitly
@customElement({ name: 'my-element', processContent: MyElement.processContent })
export class MyElement {
static processContent(node: INode, platform: IPlatform) { }
}
// ... or use a static method named 'processContent' (convention)
@customElement({ name: 'my-element' })
export class MyElement {
static processContent(node: INode, platform: IPlatform) { }
}import { customElement, INode, IPlatform, processContent } from '@aurelia/runtime-html';
// Reference a static method
@processContent(MyElement.processContent)
export class MyElement {
static processContent(node: INode, platform: IPlatform) { }
}
// ...or a standalone method
function processContent(this: typeof MyElement, node: INode, platform: IPlatform) { }
@processContent(processContent)
export class MyElement {
}
// ...or the method-level decorator
export class MyElement {
@processContent()
static processContent(node: INode, platform: IPlatform) { }
}<!--tabs.html-->
<div class="header">
<au-slot name="header"></au-slot>
</div>
<div class="content">
<au-slot name="content"></au-slot>
</div><!--app.html-->
<tabs>
<tab header="Tab one">
<span>content for first tab.</span>
</tab>
<tab header="Tab two">
<span>content for second tab.</span>
</tab>
<tab header="Tab three">
<span>content for third tab.</span>
</tab>
</tabs>// tabs.ts
import { INode, IPlatform, processContent } from '@aurelia/runtime-html';
@processContent(Tabs.processTabs)
class Tabs {
public static processTabs(node: INode, p: IPlatform): boolean {
const el = node as Element;
// At first we prepare two templates that will provide the projections to the `header` and `content` slot respectively.
const headerTemplate = p.document.createElement('template');
headerTemplate.setAttribute('au-slot', 'header');
const contentTemplate = p.document.createElement('template');
contentTemplate.setAttribute('au-slot', 'content');
// Query the `<tab>` elements present in the `node`.
const tabs = toArray(el.querySelectorAll('tab'));
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
// Add header.
const header = p.document.createElement('button');
// Add a class binding to mark the active tab.
header.setAttribute('class.bind', `activeTabId=='${i}'?'active':''`);
// Add a click delegate to activate a tab.
header.setAttribute('click.delegate', `showTab('${i}')`);
header.appendChild(p.document.createTextNode(tab.getAttribute('header')));
headerTemplate.content.appendChild(header);
// Add content.
const content = p.document.createElement('div');
// Show the content if the tab is activated.
content.setAttribute('if.bind', `activeTabId=='${i}'`);
content.append(...toArray(tab.childNodes));
contentTemplate.content.appendChild(content);
el.removeChild(tab);
}
// Set the first tab as the initial active tab.
el.setAttribute('active-tab-id', '0');
el.append(headerTemplate, contentTemplate);
}
@bindable public activeTabId: string;
public showTab(tabId: string) {
this.activeTabId = tabId;
}
}processContent(node: INode, p: IPlatform) {
const projection = p.document.createElement('template');
projection.setAttribute('au-slot', '');
const content = projection.content;
for (const child of toArray(node.childNodes)) {
if (!(child as Element).hasAttribute('au-slot')) {
content.append(child);
}
}
if (content.childElementCount > 0) {
node.appendChild(projection);
}
}<bindable name="foo" mode="twoWay" attribute="fiz-baz"></bindable>@bindable({mode: BindingMode.twoWay, attribute: 'fiz-baz'}) foo;<template as-custom-element="foo-bar">
<bindable name='prop'></bindable>
Level One ${prop}
</template>
<foo-bar prop.bind="prop"></foo-bar>class LevelOne {
@bindable public prop: string;
}<template as-custom-element="foo-bar">
<bindable name='prop'></bindable>
Level Two ${prop}
<level-one prop="fiz baz"></level-one>
</template>
<foo-bar prop.bind="prop"></foo-bar>
<level-one prop.bind="prop"></level-one>class LevelTwo {
@bindable public prop: string;
}<level-two prop="foo2"></level-two>
<level-one prop="foo1"></level-one><foo-bar foo.bind="'John'"></foo-bar>
<template as-custom-element="foo-bar">
<bindable name="foo"></bindable>
<div> ${foo} </div>
</template><template as-custom-element="el-one">
<template as-custom-element="one-two">
1
</template>
2
<one-two></one-two>
</template>
<template as-custom-element="el-two">
<template as-custom-element="two-two">
3
</template>
4
<two-two></two-two>
</template>
<el-two></el-two>
<el-one></el-one><!--Having such custom element does not help much either.-->
<template as-custom-element="foo-bar">Does this work?</template>
<template as-custom-element="fiz-baz">Of course not!</template><div>
<template as-custom-element="foo-bar">This does not work.</template>
</div><template as-custom-element="">foo-bar</template>
<div></div><template as-custom-element="foo-bar">foo-bar1</template>
<template as-custom-element="foo-bar">foo-bar2</template>
<div></div><template as-custom-element="foo-bar">
<div>
<bindable name="prop"></bindable>
</div>
</template>
<div></div><template as-custom-element="foo-bar">
<bindable attribute="prop"></bindable>
</template>
<div></div><template as-custom-element="person-info">
<bindable name="person"></bindable>
<div>
<label>Name:</label>
<span>${person.name}</span>
</div>
<div>
<label>Address:</label>
<span>${person.address}</span>
</div>
</template>
<h2>Sleuths</h2>
<person-info repeat.for="sleuth of sleuths" person.bind="sleuth"></person-info>
<h2>Nemeses</h2>
<person-info repeat.for="nemesis of nemeses" person.bind="nemesis"></person-info>export class App {
public readonly sleuths: Person[] = [
new Person('Byomkesh Bakshi', '66, Harrison Road'),
new Person('Sherlock Holmes', '221b Baker Street')
];
public readonly nemeses: Person[] = [
new Person('Anukul Guha', 'unknown'),
new Person('James Moriarty', 'unknown')
];
}
class Person {
public constructor(
public name: string,
public address: string,
) { }
}Learn how Router-Lite handles the re-entrance of the same component and how to override the default behavior.
The transition plan in router-lite is meant for deciding how to process a navigation instruction that intends to load the same component that is currently loaded/active, but with different parameters. As the router-lite uses a sensible default based on the user-voice, probably you never need to touch this area. However, it is still good to know how to change those defaults, whenever you are in need to do that (and we all know that such needs will arise from time to time).
Transition plan can be configured using the transitionPlan property in the routing configuration. The allowed values are replace, invoke-lifecycles, none or a function that returns one of these values.
replace: This instructs the router to completely remove the current component and create a new one, behaving as if the component is changed. This is the default behavior if the parameters are changed.
invoke-lifecycles: This instructs the router to call the lifecycle hooks (canUnload, canLoad, unloading and loading) of the component.
none: Does nothing. This is the default behavior, when nothing is changed.
The child routes inherits the transitionPlan from the parent.
When the transitionPlan property in the routing configuration is not configured, router-lite uses replace when the parameters are changed and none otherwise.
Transition plans defined on the root are inherited by the children. The example below shows that the transitionPlan on the root is configured to replace and this transition plan is inherited by the child route configuration. This means that every time the link is clicked, the component is created new and the view reflects that as well.
import { customElement } from '@aurelia/runtime-html';
import { IRouteViewModel, route } from '@aurelia/router-lite';
@customElement({ name: 'ce-one', template: 'ce1 ${id1} ${id2}' })
class CeOne implements IRouteViewModel {
private static id1: number = 0;
private static id2: number = 0;
// Every instance gets a new id.
private readonly id1: number = ++CeOne.id1;
private id2: number;
public canLoad(): boolean {
// Every time the lifecycle hook is called, a new id is generated.
this.id2 = ++CeOne.id2;
return true;
}
}
@route({
transitionPlan: 'replace',
routes: [
{
id: 'ce1',
path: ['', 'ce1', 'ce1/:id'],
component: CeOne,
},
],
})
@customElement({
name: 'my-app',
template: `<a load="ce1">ce-one</a> <a load="ce1/1">ce-one/1</a><br><au-viewport></au-viewport>`,
})
export class MyApp {}See this example in action below.
You can use a function to dynamically select transition plan based on route nodes. The following example shows that, where for every components, apart from the root component, invoke-lifecycles transition plan is selected.
import { customElement } from '@aurelia/runtime-html';
import { IRouteViewModel, route } from '@aurelia/router-lite';
@customElement({ name: 'ce-one', template: 'ce1 ${id1} ${id2}' })
class CeOne implements IRouteViewModel {
private static id1: number = 0;
private static id2: number = 0;
// Every instance gets a new id.
private readonly id1: number = ++CeOne.id1;
private id2: number;
public canLoad(): boolean {
// Every time the lifecycle hook is called, a new id is generated.
this.id2 = ++CeOne.id2;
return true;
}
}
@route({
transitionPlan(_current: RouteNode, next: RouteNode) {
return next.component.Type === MyApp ? 'replace' : 'invoke-lifecycles';
},
routes: [
{
id: 'ce1',
path: ['', 'ce1', 'ce1/:id'],
component: CeOne,
},
],
})
@customElement({
name: 'my-app',
template: `<a load="ce1">ce-one</a> <a load="ce1/1">ce-one/1</a><br><au-viewport></au-viewport>`,
})
export class MyApp {}The behavior can be validated by alternatively clicking the links multiple times and observing that the CeOne#id2 increases, whereas CeOne#id1 remains constant. This shows that every attempt to load the CeOne only invokes the lifecycle hooks without re-instantiating the component every time. You can try out this example below.
This can be interesting when dealing with sibling viewports, as you can select different transition plan for different siblings.
import { customElement } from '@aurelia/runtime-html';
import { IRouteViewModel, route, RouteNode } from '@aurelia/router-lite';
@customElement({ name: 'ce-two', template: 'ce2 ${id1} ${id2}' })
class CeTwo implements IRouteViewModel {
private static id1: number = 0;
private static id2: number = 0;
private readonly id1: number = ++CeTwo.id1;
private id2: number;
public canLoad(): boolean {
this.id2 = ++CeTwo.id2;
return true;
}
}
@customElement({ name: 'ce-one', template: 'ce1 ${id1} ${id2}' })
class CeOne implements IRouteViewModel {
private static id1: number = 0;
private static id2: number = 0;
private readonly id1: number = ++CeOne.id1;
private id2: number;
public canLoad(): boolean {
this.id2 = ++CeOne.id2;
return true;
}
}
@route({
transitionPlan(current: RouteNode, next: RouteNode) {
return next.component.Type === CeTwo ? 'invoke-lifecycles' : 'replace';
},
routes: [
{
id: 'ce1',
path: ['ce1', 'ce1/:id'],
component: CeOne,
},
{
id: 'ce2',
path: ['ce2', 'ce2/:id'],
component: CeTwo,
},
],
})
@customElement({
name: 'ro-ot',
template: `
<a load="ce1/1@$1+ce2/1@$2">ce1/1@$1+ce2/1@$2</a>
<a load="ce1/2@$1+ce2/2@$2">ce1/2@$1+ce2/2@$2</a>
<div id="content">
<au-viewport name="$1"></au-viewport>
<au-viewport name="$2"></au-viewport>
</div>
`,
})
export class MyApp {}The example above selects invoke-lifecycles for the CeTwo and replace for everything else. When you alternatively click the links multiple times, you can see that CeOne is re-instantiated every time whereas for CeTwo only the lifecycles hooks are invoked and the instance is reused. You can see the example in action below.
In this section, we will learn how you can dynamically render components in your applications by utilizing Aurelia's dynamic composition functionality.
When using Aurelia's <au-compose> element, inside of the view model being used, you have access to all of Aurelia's standard view lifecycle events and an extra activate.
The <au-compose> element allows us to compose view/view model pairs and just views, like a custom element, without specifying a tag name.
The au-compose element can render any custom element given to its component property.
A basic example is:
When using a string value for component binding on <au-compose>, the value will be understood as a custom element name, and will be used to lookup the actual element definition. If there's no element definition found either locally or globally, an error will be thrown.
The following usages are valid:
or, suppose my-input is a globally available custom element:
Composing using a custom element definition is not always necessary or convenient. The au-compose can also work with a slightly simpler composition: either using view only or view and simple view model combination.
An example of template-only composition:
We use the <au-compose> element inside our template and pass through a view to be rendered. The view is just a plain HTML string.
During a composition, this HTML string is processed by the Aurelia template compiler to produce necessary parts for UI composition and renders it inside the <au-compose> element.
Combining simple template and literal object as the component instance, we can also have powerful rendering without boilerplate:
When composing a custom element as component, a host element will be created based on the custom element name (e.g my-input results in <my-input>). For non custom element composition, a comment will be created as the host, like in the following example:
The rendered HTML will be:
the comments <!--au-start--> and <!--au-end--> are the boundary of the composed html. Though sometimes it's desirable to have a real HTML element as the host. This can be achieved via the tag bindable property on the <au-compose> element. For example, in the same scenario above, we want to wrap the <input class='input-field'> in a <div> element with class form-field:
The rendered HTML will be:
This behavior can be used to switch between different host elements when necessary, all bindings declared on <au-compose> will be transferred to the newly created host element if there is one.
model.bindactivate method on the view model, regardless of whether a custom element or a plain object is provided, will be called during the first composition and subsequent changes of the model property on the <au-compose> element.
You can also pass an object inline from the template:
Inside the component view model being composed, the activate method will receive the object as its first argument.
Dynamic composition in Aurelia is a powerful feature allowing greater flexibility in rendering components or views dynamically based on runtime conditions. However, it's important to understand when using dynamic composition (<au-compose>) over standard components is more appropriate. Here are some scenarios where dynamic composition can be particularly advantageous:
When the content of your application needs to change dynamically based on user interactions or application state, dynamic composition is a great fit. For example, in a dashboard application where different widgets must be displayed based on user preferences, <au-compose> can dynamically load these widgets.
Suppose your application needs to render components unknown at compile time, such as in a plugin-based architecture where plugins are loaded dynamically. In that case, dynamic composition is the way to go. It allows you to render these components without hardcoding them into your application.
In cases where you need to render one of many possible views or components based on certain conditions, dynamic composition can be more efficient. Instead of using multiple if.bind statements or switch cases in your templates, you can use <au-compose> to select and render the appropriate view or component.
When creating complex layouts that are reused across different parts of your application with different content, dynamic composition can be used to inject the specific content into these layouts. This approach promotes reusability and keeps your code DRY.
In scenarios where passing numerous parameters to a component could make its interface overly complex, dynamic composition allows for encapsulating these parameters within a model object. This can simplify the interface and make the component easier to use.
Dynamic composition can help decouple the logic of which component to display from the display logic itself. This separation of concerns can make your codebase more maintainable and easier to test.
If your application is large and you want to reduce the initial load time, dynamic composition can be used to load components on demand. This lazy loading of components can significantly improve performance, especially for single-page applications with many features.
In some scenarios, you may want to access the view model of the rendered component using <au-compose>. We can achieve this by adding the component.ref(known as view-model.ref in v1) binding to our compose element.
This will work as though it were a component.ref binding on a standard custom element.
The <au-compose> will pass all bindings, except those targeting its bindable properties (model/component/template) declared on it, to the composed view model, assuming it is a custom element.
As an example, for the following scenario:
It will work as if you have the following content in app.html:
The composition in Aurelia 2 is fundamentally different from Aurelia 1. The same ease of use is still there, but how some things worked in v1 does not work the same in v2.
In Aurelia 2, the view and view-model properties have been renamed template and component respectively.
If you were having view.bind or view-model.bind, change them to template.bind or component.bind respectively.
In Aurelia 2, passing a string to the view or view-model properties no longer means module name. In Aurelia 1, the module would be resolved to a file. In v2, the view property only understands string values, and the view-model property only understands objects and classes.
If you still want a view supporting a dynamically loaded module, you can create a value converter that achieves this.
The above value converter will load the URL and return the text response. For view models, something similar can be achieved where an object or class can be returned.
In Aurelia 2, all bindings are transferred to the underlying custom element composition. Therefore, component.ref no longer signifies obtaining a reference to the composer but rather to the composed view model.
Scope-breaking changes
By default, when composing, the outer scope will not be inherited. The parent scope will only be inherited when no custom element is composed. This means the outer scope will be used when composing only a view or plain object as the view model.
You can disable this behaviour using the scope-behavior attribute.
Possible values are:
auto: in view only composition: inherit the parent scope
scoped: never inherit parent scope even in view only composition
Dependency Injection (DI) is a design pattern that allows for creating objects dependent on other objects (their dependencies) without creating those dependencies themselves. It's a way of achieving loose coupling between classes and their dependencies. Aurelia provides a powerful and flexible DI system that can greatly simplify the process of wiring up the various parts of your application.
This document aims to provide comprehensive guidance on using DI in Aurelia, complete with explanations and code examples to illustrate its use in real-world scenarios.
As a system increases in complexity, it becomes increasingly important to break complex code down into groups of smaller, collaborating functions or objects. However, once we’ve broken down a problem/solution into smaller pieces, we have introduced a new problem: how do we put the pieces together?
One approach is to have the controlling function or object directly instantiate all its dependencies. This is tedious but also introduces the bigger problem of tight coupling and muddies the controller's primary responsibility by forcing upon it a secondary concern of locating and creating all dependencies. Inversion of Control (IoC) can be employed to address these issues.
Simply put, the responsibility for locating and/or instantiating collaborators is removed from the controlling function/object and delegated to a 3rd party (the control is inverted).
Typically, this means that all dependencies become parameters of the function or object constructor, making every function/object implemented this way not only decoupled but open for extension by providing different implementations of the dependencies. Providing these dependencies to the controller is called Dependency Injection (DI).
Once again, we’re back at our original problem: how do we put all these pieces together? With the control merely inverted and open for injection, we are now stuck having to manually instantiate or locate all dependencies and supply them before calling the function or creating the object…and we must do this at every function call site or every place that the object is instanced. It seems this may be a bigger maintenance problem than we started with!
Fortunately, there is a battle-tested solution to this problem. We can use a Dependency Injection Container. With a DI container, a class can declare its dependencies and allow the container to locate and provide them to the class. Because the container can locate and provide dependencies, it can also manage the lifetime of objects, enabling singleton, transient and object pooling patterns without consumers needing to be aware of this complexity.
Constructor injection is the most common form of DI. It involves providing the dependencies of a class through its constructor.
In Aurelia, there are several ways to declare dependencies for injection into plain classes:
You can specify the dependencies by adding a static inject property to your class, which is an array of the dependencies:
The order of dependencies in the inject array must match the order of the parameters in the constructor.
With the @inject decorator, you can declare dependencies in a more declarative way:
If you use TypeScript and have enabled metadata emission, you can leverage the TypeScript compiler to deduce the types to inject:
An Aurelia application typically has a single root-level DI container. To create one:
In Aurelia, services can be registered with the container using the register API:
The register method allows you to associate a key with a value, which can be a singleton, transient, instance, callback, or alias.
Services are usually resolved automatically via constructor injection. However, you can also resolve them manually:
For multiple implementations, use getAll:
Since TypeScript interfaces do not exist at runtime, you can use a symbol to represent the interface:
Using DI.createInterface(), you can create an interface token that also strongly types the return value of get:
DI.createInterface() can take a callback to provide a default implementation:
When inheritance is involved, constructor injection may not suffice. Property injection using the resolve function can be used in such cases:
resolve Usagesresolve can also be used in factory functions or other setup logic:
Remember, resolve must be used within an active DI container context.
For those migrating from Aurelia 1, most concepts remain the same, but it is recommended to use DI.createInterface to create injection tokens for better forward compatibility and consumer friendliness.
You can inject an interface using either the decorator or the token directly:
You can explicitly create resolvers and decorators to control how dependencies are registered:
Decorators can also be used to register classes in the root or requesting container:
You can customize how dependencies are injected using additional decorators:
For injecting objects like Window with additional properties:
By following these guidelines and utilizing the powerful features of Aurelia's DI system, you can build a well-architected application with cleanly separated concerns and easily manageable dependencies.
HTML elements are special objects that often require different observation strategies, and most of the time, listening to some specific event is the preferred way. For this reason, Aurelia encourages using events to observe HTML elements.
As an example, the value property of an <input /> element should be observed by listening to the <input /> change events such as input or change on the element. Another example is the value property of a <select /> element should be observed by listening to the change event on it.
By default, the observation of HTML elements is done using a default node observer locator implementation. This default locator has a basic set of APIs that allows users to teach Aurelia how to observe HTML element observation effectively.
The following is the trimmed interface of the node observer locator, highlighting its capability to learn how to observe HTML elements:
useConfig and useConfigGlobal are two methods that can be used to teach the default node observer locator what events can be used to observe a property of a specific element or any element.
Using the nodeObserverLocator API, we can tell Aurelia how to observe properties of HTML elements for changes. Under the hood, Aurelia already observes properties like values on form inputs, but it is good to understand how this functionality works, especially for custom elements and web components.
value property of a <textarea /> element:In this example, the eventsConfig argument has the value { events: ['input', 'change']}.
length of an <input /> element:In this example, eventsConfig argument has the value { events: ['input']}.
scrollTop of all elements:In this example, eventsConfig argument has the value { events: ['scroll']}.
It should be the same as observing custom (HTML) elements and normal HTML elements. It is common for Web Components to have well-defined events associated with their custom properties, so observing them often means adding a few configuration lines.
An example of how to teach Aurelia to observe the value property of a <my-input /> element, and <my-input /> dispatches valueChanged event when its value has been changed:
<au-compose component.bind="MyField"></au-compose>import { CustomElement } from '@aurelia/runtime-html';
export class App {
MyField = CustomElement.define({
name: 'my-input',
template: '<input value.bind="value">'
})
}<import from="./my-input"></import>
<au-compose component="my-input"><au-compose component="my-input"><au-compose template="<p>Hello world</p>"></au-compose><au-compose repeat.for="i of 5" component.bind="{ value: i }" template="<div>\\${value}</div>"></au-compose><au-compose template="<input class='input-field' value.bind='value'"><!--au-start--><input class='input-field'><!--au-end--><au-compose tag='div' class='form-field' template="<input class='input-field' value.bind='value'"><div class='form-field'><input class='input-field'></div><au-compose model.bind="myObject"></au-compose><au-compose model.bind="{myProp: 'value', test: 'something'}"></au-compose>export class MyComponent {
activate(model) {
// Model contains the passed-in model object
}
}<au-compose component.ref="myCompose"></au-compose><au-compose component.bind="myInput" value.bind="item">export class MyInput {
@bindable() value
}<input value.bind="value"><my-input value.bind="item"> <au-compose template="https://my-server.com/templates/${componentName} | loadTemplate"> class LoadTemplateValueConverter {
toView(v) { return fetch(v).then(r => r.text()) }
} <au-compose scope-behavior="scoped">import { FileReader, Logger } from 'your-dependencies-path';
export class FileImporter {
public static readonly inject = [FileReader, Logger];
constructor(private fileReader: FileReader, private logger: Logger) {
// Constructor logic here
}
}import { inject, FileReader, Logger } from 'aurelia';
@inject(FileReader, Logger)
export class FileImporter {
constructor(private fileReader: FileReader, private logger: Logger) {
// Constructor logic here
}
}import { inject, FileReader, Logger } from 'aurelia';
@inject()
export class FileImporter {
constructor(private fileReader: FileReader, private logger: Logger) {
// Constructor logic here
}
}import { DI } from 'aurelia';
const container = DI.createContainer();import { DI, Registration } from 'aurelia';
const container = DI.createContainer();
container.register(
Registration.singleton(ProfileService, ProfileService),
Registration.instance(fetch, fakeFetch)
);const profileService: ProfileService = container.get(ProfileService);const panels: Panel[] = container.getAll(Panel);export const IProfileService = Symbol('IProfileService');
export interface IProfileService { /* ... */ }export const IProfileService = DI.createInterface<IProfileService>();
export interface IProfileService {
// Interface definition
}export const ITaskQueue = DI.createInterface<ITaskQueue>(x => x.singleton(TaskQueue));
export interface ITaskQueue {
// Interface definition
}import { resolve } from 'aurelia';
abstract class FormElementBase {
form = resolve(Element);
formController = resolve(FormController);
}
export class MyInput extends FormElementBase {
constructor() {
super();
// Additional setup
}
}import { resolve, all } from 'aurelia';
export function useFieldListeners(field) {
const listeners = resolve(all(IFieldListeners));
// Further logic
}export class MyComponent {
constructor(@IApiClient private api: IApiClient) {}
}
// In the future, the decorator may not be necessary:
export class MyComponent {
constructor(private api: IApiClient) {}
}Registration.singleton(key, SomeClass);
Registration.transient(key, SomeClass);
// And so on...@singleton
export class SomeClass {}
@singleton({ scoped: true })
export class SomeClass {}export class MyComponent {
constructor(@all(ISink) private sinks: ISink[]) {}
constructor(@lazy(IFoo) private getFoo: () => IFoo) {}
// And so on...
}export interface IReduxDevTools extends Window {
devToolsExtension?: DevToolsExtension;
}
export class MyComponent {
constructor(@IWindow private window: IReduxDevTools) {}
}export class NodeObserverLocator {
allowDirtyCheck: boolean;
handles(obj, key, requestor): boolean;
useConfig(config): void;
useConfig(nodeName, key, eventsConfig): void;
useConfigGlobal(config): void;
useConfigGlobal(key, eventsConfig): void;
}nodeObserverLocator.useConfig('textarea', 'value', { events: ['input', 'change'] });nodeObserverLocator.useConfig('input', 'length', { events: ['input'] });nodeObserverLocator.useConfigGlobal('scrollTop', { events: ['scroll'] });nodeObserverLocator.useConfig('my-input', 'value', { events: ['valueChanged'] });Sometimes developers want to simulate the situation they have experienced in other frameworks in Aurelia, like Angular or Vue binding syntax. Aurelia provides an API that allows you to change how it interprets templating syntax and even emulate other framework syntax with ease.
attributePattern decorator in the form of extensibility feature in Aurelia. With it, we can introduce our own syntax to Aurelia's binding engine.
export function attributePattern(...patternDefs: AttributePatternDefinition[]): AttributePatternDecorator {
// ...
}
export interface AttributePatternDefinition {
pattern: string;
symbols: string;
}Its parameters are as follows
pattern
You define the pattern of your new syntax in terms of a very special keyword, PART. That's essentially the equivalent of this regex: (.+).
symbols
In symbols you put anything that should not be included in part extraction, anything that makes your syntax more readable but plays no role but separator e.g. in value.bind syntax, the symbols is . which sits there just in terms of more readability, and does not play a role in detecting parts of the syntax.
Consider the following example:
@attributePattern({ pattern: 'foo@PART', symbols: '@' })foo@bar would give you the parts foo and bar, but if you omitted symbols, then it would give you the parts foo@ and bar.
This attribute should be on top of a class, and that class should have methods whose name matches the pattern property of each pattern you have passed to the attributePattern. Consider the following example:
// attr-patterns.ts
@attributePattern({ pattern: '[(PART)]', symbols: '[()]' })
export class AngularTwoWayBindingAttributePattern {
public ['[(PART)]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
}
}<!-- Angular two-way binding usage -->
<input [(value)]="message">We have defined the Angular two-way binding pattern, [(PART)], the symbols are [()] which behaves as a syntax sugar for us; the public method defined in the body of the class has the same name as the pattern defined.
This method also accepts three parameters, rawName, rawValue, and parts.
rawName
Left-side of assignment.
rawValue
Right-side of assignment.
parts
The values of PARTs of your pattern without symbols.
rawName: "[(value)]"
rawValue: "message"
parts: ["value"]
The ref binding command to create a reference to a DOM element. In Angular, this is possible with #. For instance, ref="uploadInput" has #uploadInput equivalent in Angular.
@attributePattern({ pattern: '#PART', symbols: '#' })
export class SharpRefAttributePattern {
public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, parts[0], 'element', 'ref');
}
}Given the above example and the implementation, the parameters would have values like the following:
<!-- #uploadInput="" -->
<input type="file" #uploadInput/>rawName: "#uploadInput"
rawValue: "" , an empty string.
parts: ["uploadInput"]
If we want to extend the syntax for ref.view-model="uploadVM", for example, we could just add another pattern to the existing class:
@attributePattern(
{ pattern: 'PART#PART', symbols: '#' }, // e.g. view-model#uploadVM
{ pattern: '#PART', symbols: '#' } // e.g. #uploadInput
)
export class AngularSharpRefAttributePattern {
public ['PART#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, parts[1], parts[0], 'ref');
}
public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, parts[0], 'element', 'ref');
}
}It is up to you to decide how each PART will be taken into play.
You can register attributePattern in the following two ways:
Globally
Go to the main.ts or main.js and add the following code:
import {
AngularTwoWayBindingAttributePattern
} from './attr-patterns';
Aurelia
.register(
AngularTwoWayBindingAttributePattern
)
.app(MyApp)
.start();Locally
You may want to use it in a specific part of your application. You can introduce it through dependencies.
Import from somewhere else:
import { AngularTwoWayBindingAttributePattern } from "./attr-patterns";
@customElement({
name: 'foo',
template,
/* HERE */
dependencies: [
AngularTwoWayBindingAttributePattern
]
})Define it inline:
@customElement({
name: 'foo',
template
/* HERE */
dependencies: [
AttributePattern.define(class { ['!PART'](n, v, [t]) { return new AttrSyntax(n, v, t, 'bind') } }
]
})// attr-patterns.ts
import { attributePattern, AttrSyntax } from '@aurelia/runtime-html';
// Angular
@attributePattern({ pattern: '#PART', symbols: '#' })
export class AngularSharpRefAttributePattern {
public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, parts[0], 'element', 'ref');
}
}
@attributePattern({ pattern: '[PART]', symbols: '[]' })
export class AngularOneWayBindingAttributePattern {
public ['[PART]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'to-view' /*'bind'*/);
}
}
@attributePattern({ pattern: '(PART)', symbols: '()' })
export class AngularEventBindingAttributePattern {
public ['(PART)'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'trigger');
}
}
@attributePattern({ pattern: '[(PART)]', symbols: '[()]' })
export class AngularTwoWayBindingAttributePattern {
public ['[(PART)]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
}
}
// Vue
@attributePattern({ pattern: '[PART]', symbols: ':' })
export class VueOneWayBindingAttributePattern {
public [':PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'to-view' /*'bind'*/);
}
}
@attributePattern({ pattern: '@PART', symbols: '@' })
export class VueEventBindingAttributePattern {
public ['@PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'trigger');
}
}
@attributePattern({ pattern: 'v-model', symbols: '' })
export class VueTwoWayBindingAttributePattern {
public ['v-model'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, 'value', 'two-way');
}
}
// Vue+
@attributePattern({ pattern: '::PART', symbols: '::' })
export class DoubleColonTwoWayBindingAttributePattern {
public ['::PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
}
}
// main.ts
import {
AngularEventBindingAttributePattern,
AngularOneWayBindingAttributePattern,
AngularSharpRefAttributePattern,
AngularTwoWayBindingAttributePattern,
DoubleColonTwoWayBindingAttributePattern,
VueEventBindingAttributePattern,
VueOneWayBindingAttributePattern,
VueTwoWayBindingAttributePattern
} from './attr-patterns';
Aurelia
.register(
AngularSharpRefAttributePattern,
AngularOneWayBindingAttributePattern,
AngularEventBindingAttributePattern,
AngularTwoWayBindingAttributePattern,
VueOneWayBindingAttributePattern,
VueEventBindingAttributePattern,
VueTwoWayBindingAttributePattern,
DoubleColonTwoWayBindingAttributePattern
)
.app(MyApp)
.start();The Event Aggregator is a pub/sub-event package that allows you to publish and subscribe to custom events inside your Aurelia applications. Some parts of the Aurelia framework use the event aggregator to publish certain events at various stages of the lifecycle and actions taking place.
To use the Event Aggregator, we inject the IEventAggregator interface into our component. We inject it as IEventAggregator on our component class in the following code example.
import { ICustomElementViewModel, IEventAggregator } from 'aurelia';
export class MyComponent implements ICustomElementViewModel {
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
} The Event Aggregator provides a subscription method to subscribe to published events.
import { ICustomElementViewModel, IEventAggregator } from 'aurelia';
export class MyComponent implements ICustomElementViewModel {
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
bound() {
this.ea.subscribe('event name', payload => {
// Do stuff inside of this callback
});
}
} Sometimes, you might only want to subscribe to an event once. To do that, we can use the subscribeOnce method to listen to the event and dispose of itself once it has been fired.
import { ICustomElementViewModel, IEventAggregator } from 'aurelia';
export class MyComponent implements ICustomElementViewModel {
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
bound() {
this.ea.subscribeOnce('event name', payload => {
// Do stuff inside of this callback just once
});
}
} To publish (emit) an event, we use the publish method. You can provide an object to the publish method, which allows you to emit data via the event (accessible as a parameter on the subscribe method).
import { ICustomElementViewModel, IEventAggregator } from 'aurelia';
export class MyComponent implements ICustomElementViewModel {
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
bound() {
const payload = {
component: 'my-component',
prop: 'value',
child: {
prop: 'value'
}
};
this.ea.publish('component bound', payload);
}
} It's considered best practice to dispose of your event listeners when you are finished with them. Inside a component, you would usually do this inside of the unbinding method. The event will be of type IDisposable that we will use to type our class property strongly.
import { ICustomElementViewModel, IEventAggregator, IDisposable } from 'aurelia';
export class MyComponent implements ICustomElementViewModel {
private myEvent: IDisposable;
constructor(@IEventAggregator readonly ea: IEventAggregator) {
}
bound() {
this.myEvent = this.ea.subscribe('event name', payload => {
// Do stuff inside of this callback
});
}
unbinding() {
this.myEvent.dispose();
}
} Always clean up after yourself. Like native Javascript events, you should dispose of any events properly to avoid memory leaks and other potential performance issues in your Aurelia applications.
Testing is integral to modern software development, ensuring that your code behaves as expected in various scenarios. Aurelia 2 facilitates testing by providing helper methods and utilities to instantiate the framework in a test environment. While Aurelia supports different test runners, such as Jest and Mocha, the core testing principles remain consistent across these tools.
Aurelia's dedicated testing library, @aurelia/testing, offers helpful functions for testing, including fixture creation methods that instantiate components with ease and handle both setup and teardown processes.
In Aurelia, testing often involves integration tests where you interact with the DOM and observe changes to content, rather than pure unit tests, which focus solely on isolated logic. It's important to test the behavior of code within the context of the view, but unit testing individual pieces of logic is also highly recommended for a comprehensive test suite.
Setting up a consistent test environment is crucial to ensure tests run correctly in different environments. This setup involves initializing the Aurelia platform using the setPlatform method and configuring the Aurelia application's environment to operate within the test runner.
Place the following initialization code in a shared file to be loaded by all your tests, or include it in each individual test suite:
import { BrowserPlatform } from '@aurelia/platform-browser';
import { setPlatform } from '@aurelia/testing';
// This function sets up the Aurelia environment for testing
export function bootstrapTestEnvironment() {
const platform = new BrowserPlatform(window);
setPlatform(platform);
BrowserPlatform.set(globalThis, platform);
}By creating the bootstrapTestEnvironment function, you can easily initialize the test environment at the beginning of each test suite. This approach ensures consistency and reduces code duplication:
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';
beforeAll(() => {
// Initialize the test environment before running the tests
bootstrapTestEnvironment();
});
// ... your test suitesWith your test environment configured, you can now focus on writing effective tests for your Aurelia components, ensuring that they perform as intended under various conditions.
Event binding in Aurelia 2 provides a seamless way to handle DOM events within your application. By attaching event listeners directly in your view templates, you can easily respond to user interactions such as clicks, key presses, and more. This guide will delve into the specifics of event binding in Aurelia 2, offering detailed explanations and examples to enhance your understanding and usage of this feature.
Aurelia 2 simplifies the process of binding events to methods in your view model. It uses a straightforward syntax that allows you to specify the type of event and the corresponding method to invoke when that event occurs.
The general syntax for event binding in Aurelia 2 is as follows:
element represents the HTML element to which you want to attach the event listener.
event is the event you want to listen for (e.g., click, keypress).
.trigger is the binding command that tells Aurelia to listen for the specified event and call the method when the event is fired.
methodName is the method's name in your view-model that will be called when the event occurs.
argument1, argument2, ... are optional arguments you can pass to the method.
Aurelia 2 offers two primary commands for event binding:
.trigger: This command attaches an event listener that responds to events during the bubbling phase. It is the most commonly used event-binding command and is suitable for most use cases.
.capture: This command listens for events during the capturing phase. It is generally reserved for special circumstances, such as when you need to intercept events before they reach a target element that may prevent their propagation.
To listen for a click event on a button and call a method named handleClick, you would write:
When the button is clicked, your view-model's handleClick method will be executed.
You can pass the event object itself or other custom data to your event handler method. For instance, to pass the event object to the handleClick method, you would modify the binding like this:
In your view model, the handleClick method would accept the event object as a parameter:
Aurelia 2 allows you to bind to any standard DOM event. Here are some common events you might use:
The click event is frequently used for buttons, links, and other clickable elements.
The keypress event is useful for responding to user input in text fields or when handling keyboard navigation.
The mouseover event can trigger interactions when the user hovers over an element.
Sometimes, you may want to stop an event from bubbling up the DOM tree or prevent the default action associated with that event. You can do this within your event handler methods using the event object's methods:
event.stopPropagation(): Prevents further propagation of the event in the bubbling or capturing phase.
event.preventDefault(): Cancels the event if it is cancelable without stopping further propagation.
While the .trigger and .capture commands cover most use cases, Aurelia 2 also allows for more advanced scenarios, such as throttling event handlers for performance reasons or handling custom events.
To improve performance, especially for events that can fire rapidly like mousemove or scroll, you can throttle the event handler invocation using Aurelia's binding behaviors.
In the above example, the handleMouseMove method will be called at most once every 100 milliseconds, no matter how often the mousemove event is fired.
Aurelia 2 supports custom events, which can be useful when integrating with third-party libraries or creating your own custom components.
In this example, my-event is a custom event emitted by custom-element, and handleCustomEvent is the method that will respond to it.
To help you better understand event binding in Aurelia 2, we've compiled a collection of examples and scenarios demonstrating different techniques and best practices. These should give you the insights to handle events in your applications effectively.
To ensure that an event only triggers a method if the event originated from the element itself (and not from its children), you can use the self binding behavior.
This setup guarantees that clicking the button will not trigger the divClicked() method, as the self binding behaviour filters out events bubbling from child elements.
A checkbox's change in state can be combined with the change event to perform actions in response to user interaction.
To react to specific key presses, such as "Enter" or "Escape", you can inspect the event object within your method.
Event delegation is useful for handling events on dynamically generated content, such as a list of items.
Custom elements can publish custom events with associated data, which parent components can listen for and handle.
Custom element:
Parent component:
Parent view-model:
For features like search or autocomplete, where user input can trigger frequent updates, throttling can prevent excessive processing.
Here, the search function is called only after the user has stopped typing for 300 milliseconds, improving performance and user experience.
These examples showcase the versatility of event binding in Aurelia 2. By understanding and applying these patterns, you can create interactive and efficient applications that respond to user actions in a controlled and performant manner.
When you need to ensure some conditions are met before processing an event, you can use event modifiers. Event modifiers can be specified via event syntax, follow by a colon and modifiers:
By default, Aurelia handles 2 set of common events: mouse and keyboard events. An example is as follow:
In the example above, the handler onCtrlClick() will only be called when the button is clicked while the Ctrl key being pressed. Keyboard event sometimes employ even more complex condition, as per the following example:
In this example, we will only call send() when the user hits the Enter + Ctrl key combo. This example also demonstrates how to use multiple modifiers, they can be separated by the character + as delimiter.
preventDefault and stopPropagation are two functions commonly called on any events. Event modifiers can be used to declaratively and easily call those functions, as per following example:
When handling mouse event, it sometimes requires a specific mouse button. By default, Aurelia provides 3 modifiers left, middle and right to support mouse button verification. An example is as follow:
When using keyboard event modifier, sometimes a certain key is used as modifier. You can use the char code representing the key as the modifier, like the following example, where we want to handle the combo Ctrl + K (notice its the upper K):
75 is the charcode of the upper case letter K.
Even though direct, it's not always clear 75 means when looking at the template, so it's often desirable to use the real letter K instead. Though Aurelia is not taught to, by default, understand the letter K means the code 75. You can teach Aurelia by adding to the IKeyMapping:
After this enhancement, the :ctrl+upper_k modifier will be understood as ctrl+75 or ctrl + upper K key.
Note that we cannot use the upper case letter K as modifier in HTML because HTML is case insensitive. We use, in this example, upper_k as an alternative for that, and add the mapping accordingly.
Event binding in Aurelia 2 is a powerful and intuitive feature that enables you to create dynamic and responsive applications. By understanding the syntax and capabilities of event binding, you can harness the full potential of Aurelia 2 to handle user interactions gracefully and effectively. Remember to leverage the .trigger command for most scenarios and reserve .capture for special cases where you need to intercept events earlier in the event propagation cycle. With these tools, you can craft a seamless user experience that responds to every click, keypress, and interaction.
Use value converters to transform how values are displayed in your applications. You can use value converters to transform strings, format dates, currency display and other forms of manipulation. They can be used within interpolation and bindings, working with data to and from the view.
If you have worked with other libraries and frameworks, you might know value converters by another name; pipes.
Most commonly, you'll create value converters that translate model data to a format suitable for the view; however, there are situations where you'll need to convert data from the view to a format expected by the view model, typically when using two-way binding with input elements.
The toView method always receives the supplied value as the first argument, and subsequent parameters are configuration values (if applicable). This specifies what happens to values going to the view and allows you to modify them before display.
The fromView method always receives the supplied value as the first argument, and subsequent parameters are configuration values (if applicable). This specifies what happens to values going out of the view to the view model and allows you to modify them before the view model receives the changed value.
To apply a value converter, you use the pipe | character followed by the name of the value converter you want to use. If you have worked with Angular before, you would know value converters as pipes.
While Aurelia itself comes with no prebuilt value converters, this is what using them looks like for an imaginary value converter that converts a string to lowercase.
The code for this value converter might look something like this:
Value converters can be chained, meaning you can transform a value and then transform it through another value converter. To chain value converters, you separate your value converters using the pipe |. In this fictitious example, we are making our value lowercase and then running it through another value converter called bold which will wrap it in strong tags to make it bold.
You can also create value converters that accept one or more parameters. For value converters that format data, you might want to allow the developer to specify what that format is for, say, a currency or date formatting value converter.
Parameters are supplied using the colon : character, and like the pipe, for multiple parameters, you can chain them. Parameters can be supplied as one or more strings (passed to the value converter method as one or more arguments) or a singular object.
Furthermore, value converter parameters also support bound values. Unlike other types of binding, you only have to supply the variable, which will bind it for you.
If your value converter is going to have a lot of parameters, the existing approaches will fall apart quite quickly. You can specify your value converters take a single object of one or more parameters. Object parameters will also let you name them, unlike other parameters.
On our fromView and toView methods, the second argument will be the supplied object we can reference.
Create custom value converters that allow you to format how your data is displayed and retrieved in your views.
Like everything else in Aurelia, a value converter is a class. A value converter that doesn't do anything might look like this. Nothing about this example is Aurelia-specific and is valid in Javascript.
Value converters are always referenced as camelCase when used in your templates.
To teach you how value converters can be created, we will create a simplistic value converter called date, allowing us to format dates.
In this example, we will use a decorator valueConverter to decorate our class. While you can use the ValueConverter naming convention as we did above, it's important to learn the different ways you can create value converters.
Import your value converter in your view
This example value below will display June 22, 2021 in your view. Because our default date format is US, it will display as month-date-year.
The locale parameter we specified in our value converter supports a locale parameter, allowing us to change how our dates are displayed. Say you're in the UK or Australia. The default format is date-month-year.
To see our value converter in action, here is what it looks like:
To further highlight how useful value converters are, we will provide examples of different value converters you can use in your Aurelia applications.
Formats a number as a currency string.
Converts specific keywords or phrases to emojis.
Converts regular text into 'leet' or '1337' speak, a form of internet slang.
Flips the text upside down.
Appends an ordinal suffix to a number (e.g., 1st, 2nd, 3rd, etc.).
Converts text to Morse code.
These fun and unique value converters showcase the versatility of Aurelia's templating engine and provide an enjoyable and engaging way for developers to learn about custom value converters.
Using built-in custom attributes and building your own.
A custom attribute allows you to create special properties to enhance and decorate existing HTML elements and components. Natively attributes exist in the form of things such as disabled on form inputs or aria text labels. Where custom attributes can be especially useful is wrapping existing HTML plugins that generate their own markup.
On a simplistic level, custom attributes resemble quite a lot. They can have , and they use classes for their definitions.
A basic custom attribute looks something like this:
If you were to replace CustomAttribute with CustomElement, it would be a component. On a core level, custom attributes are a more primitive component form.
Let's create a custom attribute that adds a red background and height to any dom element it is used on:
Now, let's use our custom attribute:
We import our custom attribute so the DI knows about it and then use it on an empty DIV. We'll have a red background element with a height of one hundred pixels.
The customAttribute decorator allows you to create custom attributes, including the name explicitly. Other configuration options include the ability to create aliases.
You can explicitly name the custom attribute using the name configuration property.
The customAttribute allows you to create one or more aliases that this attribute can go by.
We can now use our custom attribute using the registered name red-square as well as redify and redbox the following example highlights using both aliases on an element.
Sometimes, you want a custom attribute with only one bindable property. You don't need to define the bindable property explicitly to do this, as Aurelia supports custom attributes with single-value bindings.
The value property is automatically populated if a value is supplied to a custom attribute, however, requires you to define the value property as a bindable explicitly.
When the value is changed, we can access it like this:
When using the custom attribute on a dom element, there are instances where you want to be able to access the element itself. To do this, you can use the INode decorator and HTMLElement interface to inject and target the element.
The code above was lifted from the first example, allowing us to access the element itself on the class using this.element This is how we can set CSS values and perform other modifications, such as initialising third-party libraries like jQuery and other libraries.
In many cases, you might only need custom attributes without user-configurable properties. However, in some cases, you want the user to be able to pass in one or more properties to change the behavior of the custom attribute (like a plugin).
Using bindable properties, you can create a configurable custom attribute. Taking our example from above, let's make the background color configurable instead of always red. We will rename the attribute for this.
We can now provide a color on a per-use basis. Let's go one step further and allow the size to be set too.
We have code that will work on the first initialization of our custom property, but if the property is changed after rendering, nothing else will happen. We need to use the change detection functionality to update the element when any bindable properties change.
As a default convention, bindable property change callbacks will use the bindable property name followed by a suffix of Changed at the end. The change callback gets two parameters, the new value and the existing value.
Whenever our size or color bindable properties change, our element will be updated accordingly instead of only at render.
Options binding provides a custom attribute with the ability to have multiple bindable properties. Each bindable property must be specified using the bindable decorator. The attribute view model may implement an optional ${propertyName}Changed(newValue, oldValue) callback function for each bindable property.
When binding to these options, separate each option with a semicolon and supply a binding command or literal value, as in the example below. It is important to note that bindable properties are converted to dash-case when used in the DOM, while the view model property they are bound to is kept with their original casing.
To use options binding, here is how you might configure those properties:
When you have more than one bindable property, you might want to specify which property is the primary one (if any). If you mostly expect the user only to configure one property most of the time, you can specify it is the primary property through the bindable configuration.
The above example specifies that color is the primary bindable property. Our code actually doesn't change at all. The way we consume the custom attribute changes slightly.
Or, you can bind the value itself to the attribute:
Learn how to work with collections of data like arrays and maps. The repeat.for functionality allows you to loop over collections of data and work with their contents similar to a Javascript for loop.
Aurelia supports working with different types of data. Array, Set, and Map are all supported collection types that can be iterated in your templates.
repeat.forYou can use the repeat.for binding to iterate over data collections in your templates. Think of repeat.for as a for loop. It can iterate arrays, maps and sets.
Breaking this intuitive syntax down, it works like this:
Loop over every item in the items array
Store each iterative value in the local variable item on the left-hand side
For each iteration, make the current item available
If you were to write the above in Javascript form, it would look like this:
When working with the repeat.for attribute in Aurelia, the key attribute specifies the property that uniquely identifies each item in the collection. Aurelia uses this property to track changes in the collection and efficiently update the DOM accordingly.
To use the key attribute, add it to the repeater element and bind it to a unique property of each item in the collection. You can use either literal or expression syntax:
In this example, id is the property name Aurelia will use to uniquely identify each item in the items collection.
The key attribute serves the following purposes:
Change Tracking: Aurelia tracks changes in the collection using the specified property. When an item is added, removed, or reordered, Aurelia compares the key property values to determine which items have changed.
Minimal DOM Updates: Aurelia can minimize the number of DOM manipulations required when updating the rendered list by tracking changes based on the key property. It can reuse existing elements and only make necessary changes.
Preservation of Element State: When an item's position in the collection changes, Aurelia can preserve the state of the corresponding rendered element (such as focus, scroll position, or user input) by matching the key property values.
When selecting the property to use as the key, consider the following guidelines:
The property should have unique values for each item in the collection.
The property should be stable and not change over time for a given item.
Avoid using the item's index as the key unless the collection is static and the order of items does not change.
Common choices for the key property include unique identifiers like ID or a combination of properties that uniquely identify an item.
The key attribute in Aurelia repeaters specifies the property that uniquely identifies each collection item. By setting the key attribute, Aurelia can track changes, update the DOM, and preserve the element state when rendering dynamic lists.
Choose a property that provides unique and stable values for each item in the collection to ensure optimal performance and avoid unwanted side effects.
repeat.forAurelia's binding engine makes several special properties available in your binding expressions. Some properties are available everywhere, while others are only available in a particular context.
Below is a summary of the available contextual properties within repeats.
In a repeat template, the item's index is in the collection. The index is zero-indexed, meaning the value starts from zero and increments by one for each iteration in the repeat.for loop. The following example $index will be 0 for the first iteration, then 1 and so forth.
In a repeat template, the $first variable will be true if this is the first iteration in the repeat.for loop. If the iteration is not the first iteration, then this value will be false.
In a repeat template the $last variable will be true if this is the last iteration in the repeat.for loop. This means we have reached the final item in the collection we are iterating. If the loop is continuing, this value will be false.
In a repeat template the $even variable will be true if we are currently at an even-numbered index inside the repeat.for loop. You would use this functionality when performing conditional logic (alternate row styling on table rows and so forth).
In a repeat template, the $odd variable will be true if we are currently at an odd-numbered index inside the repeat.for loop. You would use this functionality when performing conditional logic (alternate row styling on table rows).
In a repeat template the $length variable will provide the length of the collection being iterated. This value should not change throughout iterating over the collection and represents the length of the collection akin to (Array.length).
Explicitly accesses the outer scope from within a repeat.for template. In most instances where you are dealing with the value of the collection you are iterating, the $parent variable will not be needed.
You may need this when a property on the current scope masks a property on the outer scope. Note that this property is chainable, e.g. $parent.$parent.foo is supported.
These can be accessed inside the repeat.for. In the following example, we display the current index value.
You would need this functionality when dealing with multiple levels of repeat.for aka nested repeaters. As each repeat.for creates its own scope, you need to use $parent to access the outer scope of the repeater.t
In this section, see how you can iterate an array using repeat.for. You will notice the syntax is the same as the examples we used above, except for a view model containing the array to show you the relationship.
The repeat.for functionality doesn't just allow you to work with collections. It can be used to generate ranges.
In the following example, we generate a range of numbers up to 10. We subtract the value from the index inside to create a reverse countdown.
The repeat.for functionality works with arrays (the collection type you will be using) and Javascript sets. The syntax for iterating sets is the same as for arrays, so nothing changes in the template, only the collection type you are working with.
One of the more useful iterables is the Map because you can directly decompose your key and value into two variables in the repeater. Although you can repeat over objects straightforwardly, Maps can be two-way bound easier than Objects, so you should try to use Maps where possible.
Please take note of the syntax in our template. Unlike repeat.for usage for Arrays and Sets, we are decomposing the key and value (as we discussed) on the repeater itself. The syntax is still familiar but slightly different.
One thing to notice in the example above is the dereference operator in [greeting, friend] - which breaks apart the map's key-value pair into greeting, the key, and friend, the value. Note that because all of our values are objects with the name property set, we can get our friend's name with ${friend.name}, just as if we were getting it from JavaScript!
In Javascript, objects are not a native collection type. However, there might be situations where you want to iterate values inside of an object. Aurelia does not provide a way of doing this, so we must create a to transform our object into an iterable format.
We take the object in our view model, friends, and run it through our keys value converter. Aurelia looks for a registered class named KeysValueConverter and tries to call its toView() method with our friend's object. That method returns an array of keys- which we can iterate.
Our value converter uses the Javascript Reflect API to get the keys of our object, returning the values in an iterable format that our repeat.for can understand. In our template, we import our value converter to use it.
The template compiler is used by Aurelia under the hood to process templates and provides hooks and APIs allowing you intercept and modify how this behavior works in your applications.
There are scenarios where an application wants to control how to preprocess a template before it is compiled. There could be various reasons, such as accessibility validation, adding debugging attributes etc...
Aurelia supports this via template compiler hooks, enabled with the default template compiler. To use these features, declare and then register the desired hooks with either global (at startup) or local container (at dependencies (runtime) or <import> with convention).
An example of declaring global hooks that will be called for every template:
compiling: this hook will be invoked before the template compiler starts compiling a template. Use this hook if there need to be any changes to a template before any compilation.
All hooks from local and global registrations will be invoked: local first, then global.
The default compiler will remove all binding expressions while compiling a template. This is to clean the rendered HTML and increase the performance of cloning compiled fragments.
Though this is not always desirable for debugging, it could be hard to figure out what element mapped to the original part of the code. To enable an easier debugging experience, the default compiler has a property debug that when set to true will keep all expressions intact during the compilation.
This property can be set early in an application lifecycle via AppTask, so that all the rendered HTML will keep their original form. An example of doing this is:
List of attributes that are considered expressions:
containerless
as-element
ref
attr with binding expression (attr.command="...")
attr with interpolation (attr="${someExpression}")
custom attribute
custom element bindables
Now that we understand how the template compiler works let's create fun scenarios showcasing how you might use it in your Aurelia applications.
If your application uses feature flags to toggle features on and off, you may want to modify templates based on these flags conditionally.
Here, elements with a data-feature attribute will be removed from the template if the corresponding feature flag is set to false, allowing for easy management of feature rollouts.
For accessibility purposes, form fields must associate label elements with matching for and id attributes. We can automate this process during template compilation.
In this use case, the hook generates a unique id for each form field that doesn't already have one and updates the corresponding label's for attribute to match. This ensures that form fields are properly labelled for screen readers and other assistive technologies.
To enhance accessibility, you might want to automatically assign ARIA roles to certain elements based on their class or other attributes to make your application more accessible without manually annotating each element.
This hook assigns the role="button" to all elements that have the .btn class and do not already have a role defined. This helps ensure that custom-styled buttons are accessible.
If your application needs to comply with strict Content Security Policies, you should ensure that inline styles are not used within your templates. A template compiler hook can help you enforce this policy.
This hook scans for any elements with inline style attributes and removes them, logging a warning for developers to take notice and refactor the styles into external stylesheets.
For performance optimization, you should implement lazy loading for images. The template compiler can automatically add lazy loading attributes to your image tags.
This hook finds all img elements without a loading attribute and sets it to lazy, instructing the browser to defer loading the image until it is near the viewport.
If your application supports multiple themes, you can use a template compiler hook to inject the relevant theme class into the root of your templates based on user preferences.
This hook adds a theme-specific class to the root element of every template, allowing for theme-specific styles to be applied consistently across the application.
The default template compiler will turn a template, either in string or already an element, into an element before the compilation. During the compilation, these APIs on the Node & Element classes are accessed and invoked:
Node.prototype.nodeType
Node.prototype.nodeName
Node.prototype.childNodes
Node.prototype.childNode
Node.prototype.firstChild
Node.prototype.textContent
Node.prototype.parentNode
Node.prototype.appendChild
Node.prototype.insertBefore
Element.prototype.attributes
Element.prototype.hasAttribute
Element.prototype.getAttribute
Element.prototype.setAttribute
Element.prototype.classList.add
If it is desirable to use the default template compiler in any environment other than HTML, ensure the template compiler can hydrate the input string or object into some object with the above APIs.
The basics of the web-component plugin for Aurelia.
Web Components are part of an ever-evolving web specification that aims to allow developers to create native self-contained components without the need for additional libraries or transpilation steps. This guide will teach you how to use Aurelia in Web Components.
To use the plugin, import the interface IWcElementRegistry interface from @aurelia/runtime-html module and start defining web-component custom elements by calling method define on the instance of IWcElementRegistry.
WC custom elements can be defined anytime, either at the application start or later. Applications are responsible for ensuring names are unique.
Extending built-in elements is supported via the 3rd parameter of the define call, like the define call on the global window.customElements.define call.
Each of WC custom element will be backed by a view model, like a normal Aurelia element component.
For each define call, a corresponding native custom element class will be created and defined.
Each bindable property on the backing Aurelia view model will be converted to a reactive attribute (via observedAttributes) and reactive property (on the prototype of the extended HTML Element class created).
Slot: [au-slot] is not supported when upgrading an existing element. slot can be used as a normal WC custom element.
Notes:
WC custom element works independently with the Aurelia component. This means the same class can be both a WC custom element and an Aurelia component. Though this should be avoided as it could result in double rendering.
containerless mode is not supported. Use extend-built-in instead if you want to avoid wrappers.
the defined WC custom elements will continue working even after the owning Aurelia application has stopped.
template info will be retrieved & compiled only once per define call. Changing it after this call won't have any effects.
bindables info will be retrieved & compiled only once per define call. Changing it after this call won't have any effects.
Defining a tick-clock element
Defining a tick-clock element using shadow DOM with open mode
Injecting the host element into the view model
Defining a tick-clock element with format bindable property for formatting
Defining a tick-clock element extending built-in div element:
<element event.trigger="methodName(argument1, argument2, ...)"><button click.trigger="handleClick()">Click me!</button><button click.trigger="handleClick($event)">Click me!</button>export class MyViewModel {
handleClick(event) {
// Handle the click event
}
}<a href="#" click.trigger="navigate()">Go somewhere</a><input type="text" keypress.trigger="validateInput($event)" /><div mouseover.trigger="showTooltip()">Hover over me!</div><div mousemove.trigger="handleMouseMove() & throttle:100">Move your mouse over me</div><custom-element my-event.trigger="handleCustomEvent($event)"></custom-element><div click.trigger="divClicked() & self">
<button click.trigger="buttonClicked()">Button</button>
</div><input type="checkbox" checked.bind="agree" change.trigger="onAgreementChange()" />export class MyViewModel {
agree = false;
onAgreementChange() {
// Logic to handle checkbox state change
}
}<input type="text" keydown.trigger="handleKeydown($event)" />export class MyViewModel {
handleKeydown(event) {
switch (event.key) {
case 'Enter':
// Handle Enter key press
break;
case 'Escape':
// Handle Escape key press
break;
// Add more cases as needed
}
}
}<ul click.trigger="listClicked($event)">
<li repeat.for="item of items" data-id="${item.id}">${item.name}</li>
</ul>export class MyViewModel {
items = []; // Your dynamic array of items
listClicked(event) {
const itemId = event.target.getAttribute('data-id');
if (itemId) {
// Logic to handle the click event on an item
}
}
}export class CustomElement {
// inject host element to dispatch custom event
host = resolve(Element);
someMethod() {
const data = { /* Payload data */ };
this.host.dispatchEvent(new CustomEvent({ detail: data }))
}
}<custom-element my-custom-event.trigger="handleCustomEvent($event)"></custom-element>export class ParentViewModel {
handleCustomEvent(event) {
const data = event.detail;
// Logic to handle the custom event and its data
}
}<input type="text" input.trigger="search($event.target.value) & debounce:300">export class MyViewModel {
search(query) {
// Logic to perform search based on query
}
}[event].trigger[:modifier]="[expression]"<button click.trigger:ctrl="onCtrlClick()">Next page</button><textarea keydown.trigger:ctrl+enter="send()"><button click.trigger:stop:prevent="validate()">Validate</button><button click.trigger:middle="newTab()">Open in new tab</button><textarea keydown.trigger:ctrl+75="openSearchDialog()">import { AppTask, IKeyMapping } from 'aurelia';
Aurelia.register(
AppTask.creating(IKeyMapping, mapping => {
mapping.keys.upper_k = 'K';
})
)import Aurelia, { TemplateCompilerHooks } from 'aurelia';
Aurelia
.register(TemplateCompilerHooks.define(class {
compiling(template: HTMLElement) {
element.querySelector('table').setAttribute(someAttribute, someValue);
}
}))import Aurelia, { templateCompilerHooks } from 'aurelia';
@templateCompilerHooks
class MyTableHook1 {
compiling(template) {...}
}
// paren ok too
@templateCompilerHooks()
class MyTableHook1 {
compiling(template) {...}
}
Aurelia.register(MyTableHook1);import Aurelia, { AppTask, ITemplateCompiler } from 'aurelia';
import { MyApp } from './my-app';
Aurelia
.register(AppTask.creating(ITemplateCompiler, compiler => compiler.debug = true))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class FeatureFlagHook {
constructor(private featureFlags: Record<string, boolean>) {}
compiling(template: HTMLElement) {
const featureElements = template.querySelectorAll('[data-feature]');
for (const element of featureElements) {
const featureName = element.getAttribute('data-feature');
if (!this.featureFlags[featureName]) {
element.parentNode.removeChild(element);
}
}
}
}
const activeFeatureFlags = {
'new-ui': true,
'beta-feature': false
};
Aurelia.register(TemplateCompilerHooks.define(new FeatureFlagHook(activeFeatureFlags)))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class FormFieldHook {
private fieldCounter = 0;
compiling(template: HTMLElement) {
const formFields = template.querySelectorAll('input, textarea, select');
for (const field of formFields) {
if (!field.hasAttribute('id')) {
const uniqueId = `form-field-${this.fieldCounter++}`;
field.setAttribute('id', uniqueId);
const label = template.querySelector(`label[for="${field.getAttribute('name')}"]`);
if (label) {
label.setAttribute('for', uniqueId);
}
}
}
}
}
Aurelia.register(TemplateCompilerHooks.define(new FormFieldHook()))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class AriaRoleHook {
compiling(template: HTMLElement) {
const buttons = template.querySelectorAll('.btn');
for (const button of buttons) {
if (!button.hasAttribute('role')) {
button.setAttribute('role', 'button');
}
}
}
}
Aurelia.register(TemplateCompilerHooks.define(new AriaRoleHook()))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class CSPHook {
compiling(template: HTMLElement) {
const elementsWithInlineStyles = template.querySelectorAll('[style]');
for (const element of elementsWithInlineStyles) {
console.warn(`Inline style removed from element for CSP compliance:`, element);
element.removeAttribute('style');
}
}
}
Aurelia.register(TemplateCompilerHooks.define(new CSPHook()))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class LazyLoadingHook {
compiling(template: HTMLElement) {
const images = template.querySelectorAll('img:not([loading])');
for (const img of images) {
img.setAttribute('loading', 'lazy');
}
}
}
Aurelia.register(TemplateCompilerHooks.define(new LazyLoadingHook()))
.app(MyApp)
.start();import Aurelia, { TemplateCompilerHooks } from 'aurelia';
class ThemeClassHook {
constructor(private currentTheme: string) {}
compiling(template: HTMLElement) {
const rootElement = template.querySelector(':root');
if (rootElement) {
rootElement.classList.add(`theme-${this.currentTheme}`);
}
}
}
const userSelectedTheme = 'dark'; // For example, a dark theme
Aurelia.register(TemplateCompilerHooks.define(new ThemeClassHook(userSelectedTheme)))
.app(MyApp)
.start();import { Aurelia, IWcElementRegistry } from 'aurelia';
Aurelia
.register(
AppTask.creating(IWcElementRegistry, registry => {
registry.define('tick-clock', class TickClock {
static template = '${message}';
constructor() {
this.time = Date.now();
}
attaching() {
this.intervalId = setInterval(() => {
this.message = `${Date.now() - this.time} seconds passed.`;
}, 1000)
}
detaching() {
clearInterval(this.intervalId);
}
})
})
)
.app(class App {})
.start();import { Aurelia, IWcElementRegistry } from 'aurelia';
Aurelia
.register(
AppTask.creating(IWcElementRegistry, registry => {
registry.define('tick-clock', class TickClock {
static template = '${message}';
static shadowOptions = { mode: 'open' };
constructor() {
this.time = Date.now();
}
attaching() {
this.intervalId = setInterval(() => {
this.message = `${Date.now() - this.time} seconds passed.`;
}, 1000)
}
detaching() {
clearInterval(this.intervalId);
}
})
})
)
.app(class App {})
.start();import { INode, Aurelia, IWcElementRegistry } from 'aurelia';
Aurelia
.register(
AppTask.creating(IWcElementRegistry, registry => {
registry.define('tick-clock', class TickClock {
static template = '${message}';
static shadowOptions = { mode: 'open' };
// all these injections result in the same instance
// listing them all here so that applications can use what they prefer
// based on HTMLElement
static inject = [INode, Element, HTMLElement];
constructor(node, element, htmlElement) {
node === element;
element === htmlElement;
this.time = Date.now();
}
attaching() {
this.intervalId = setInterval(() => {
this.message = `${Date.now() - this.time} seconds passed.`;
}, 1000)
}
detaching() {
clearInterval(this.intervalId);
}
})
})
)
.app(class App {})
.start();import { INode, Aurelia, IWcElementRegistry } from 'aurelia';
document.body.innerHTML = '<tick-clock format="short"></tick-clock>';
Aurelia
.register(
AppTask.creating(IWcElementRegistry, registry => {
registry.define('tick-clock', class TickClock {
static template = '${message}';
static shadowOptions = { mode: 'open' };
static bindables = ['format'];
// all these injections result in the same instance
// listing them all here so that applications can use what they prefer
// based on HTMLElement
static inject = [INode, Element, HTMLElement];
constructor(node, element, htmlElement) {
node === element;
element === htmlElement;
this.time = Date.now();
}
attaching() {
this.intervalId = setInterval(() => {
this.message = `${(Date.now() - this.time)/1000} ${this.format === 'short' ? 's' : 'seconds'} passed.`;
}, 1000)
}
detaching() {
clearInterval(this.intervalId);
}
})
})
)
.app(class App {})
.start();import { Aurelia, IWcElementRegistry } from 'aurelia';
document.body.innerHTML = '<div is="tick-clock"></div>'
Aurelia
.register(
AppTask.creating(IWcElementRegistry, registry => {
registry.define('tick-clock', class TickClock {
static template = '${message}';
constructor() {
this.time = Date.now();
}
attaching() {
this.intervalId = setInterval(() => {
this.message = `${Date.now() - this.time} seconds passed.`;
}, 1000)
}
detaching() {
clearInterval(this.intervalId);
}
})
}, { extends: 'div' })
)
.app(class App {})
.start();export class CustomPropertyCustomAttribute {
} import { INode } from 'aurelia';
export class RedSquareCustomAttribute {
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = 'red';
}
}<import from="./red-square"></import>
<div red-square></div> import { customAttribute, INode } from 'aurelia';
@customAttribute({ name: 'red-square' })
export class RedSquare {
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = 'red';
}
} import { customAttribute, INode } from 'aurelia';
@customAttribute({ name: 'red-square', aliases: ['redify', 'redbox'] })
export class RedSquare {
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = 'red';
}
}<div redify></div>
<div redbox></div> import { INode } from 'aurelia';
export class RedSquareCustomAttribute {
private value;
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = 'red';
}
bind() {
this.element.style.backgroundColor = this.value;
}
} import { bindable, INode } from 'aurelia';
export class RedSquareCustomAttribute {
@bindable() private value;
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = 'red';
}
bound() {
this.element.style.backgroundColor = this.value;
}
valueChanged(newValue: string, oldValue: string){
this.element.style.backgroundColor = newValue;
}
} import { INode } from 'aurelia';
export class RedSquareCustomAttribute {
constructor(@INode private element: HTMLElement){
}
} import { bindable, INode } from 'aurelia';
export class ColorSquareCustomAttribute {
@bindable() color: string = 'red';
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = '100px';
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.backgroundColor = this.color;
}
} import { bindable, INode } from 'aurelia';
export class ColorSquareCustomAttribute {
@bindable() color: string = 'red';
@bindable() size: string = '100px';
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
} import { bindable, INode } from 'aurelia';
export class ColorSquareCustomAttribute {
@bindable() color: string = 'red';
@bindable() size: string = '100px';
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
colorChanged(newColor, oldColor) {
this.element.style.backgroundColor = newColor;
}
sizeChanged(newSize: string, oldSize: string) {
this.element.style.width = this.element.style.height = newSize;
}
} import { bindable, INode } from 'aurelia';
export class ColorSquareCustomAttribute {
@bindable() color: string = 'red';
@bindable() size: string = '100px';
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
colorChanged(newColor, oldColor) {
this.element.style.backgroundColor = newColor;
}
sizeChanged(newSize: string, oldSize: string) {
this.element.style.width = this.element.style.height = newSize;
}
} <import from="./color-square"></import>
<div color-square="color.bind: myColor; size.bind: mySize;"></div> import { bindable, INode } from 'aurelia';
export class ColorSquareCustomAttribute {
@bindable( {primary: true} ) color: string = 'red';
@bindable() size: string = '100px';
constructor(@INode private element: HTMLElement){
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
bound() {
this.element.style.width = this.element.style.height = this.size;
this.element.style.backgroundColor = this.color;
}
colorChanged(newColor, oldColor) {
this.element.style.backgroundColor = newColor;
}
sizeChanged(newSize, oldSize) {
this.element.style.width = this.element.style.height = newSize;
}
} <import from="./color-square"></import>
<div color-square="blue"></div><import from="./color-square"></import>
<div color-square.bind="myColour"></div><ul>
<li repeat.for="item of items">${item.name}</li>
</ul>for (let item of items) {
console.log(item.name);
}<!-- Literal syntax -->
<ul>
<li repeat.for="item of items; key: id">
${item.name}
</li>
</ul>
<!-- Expression syntax -->
<ul>
<li repeat.for="item of items; key.bind: item.id">
${item.name}
</li>
</ul><ul>
<li repeat.for="item of items">${$index}</li>
</ul><ul>
<li repeat.for="item of items">${$first}</li>
</ul><ul>
<li repeat.for="item of items">${$last}</li>
</ul><ul>
<li repeat.for="item of items">${$even}</li>
</ul><ul>
<li repeat.for="item of items">${$odd}</li>
</ul><ul>
<li repeat.for="item of items">${$length}</li>
</ul><ul>
<li repeat.for="item of items">${$parent.$index}</li>
</ul>class MyComponent {
items = [
{name: 'John'},
{name: 'Bill'},
]
}<li repeat.for="item of items">${item.name}</li><p repeat.for="i of 10">${10-i}</p>
<p>Blast Off!<p>export class RepeaterTemplate {
friends: Set<string> = new Set();
constructor() {
this.friends.add('Alice');
this.friends.add('Bob');
this.friends.add('Carol');
this.friends.add('Dana');
}
}<template>
<p repeat.for="friend of friends">Hello, ${friend}!</p>
</template>export class RepeaterTemplate {
friends = new Map();
constructor() {
this.friends.set('Hello', { name: 'Alice' });
this.friends.set('Hola', { name: 'Bob' });
this.friends.set('Ni Hao', { name: 'Carol' });
this.friends.set('Molo', { name: 'Dana' });
}
}<p repeat.for="[greeting, friend] of friends">${greeting}, ${friend.name}!</p><p repeat.for="greeting of friends | keys">${greeting}, ${friends[greeting].name}!</p>export class RepeaterTemplate {
constructor() {
this.friends = {
'Hello':
{ name : 'Alice' },
'Hola':
{ name : 'Bob' },
'Ni Hao':
{ name : 'Carol' },
'Molo':
{ name : 'Dana' }
}
}
}// resources/value-converters/keys.ts
export class KeysValueConverter {
toView(obj): string[] {
return Reflect.ownKeys(obj);
}
}<import from="resources/value-converters/keys"></import>
<p repeat.for="greeting of friends | keys">${greeting}, ${friends[greeting].name}!</p>Components are the building blocks of Aurelia applications. This guide covers the essentials of creating, configuring, and using components, complete with practical code examples.
Custom elements are the foundation of Aurelia applications. As a developer, you'll often create custom elements that consist of:
An HTML template (view)
A class acting as the view model
An optional CSS stylesheet
Naming Components
The component name, derived from the file name, must include a hyphen to comply with the Shadow DOM specifications (see Styling Components). This requirement is part of the W3C Web Components standard to ensure proper namespacing for custom HTML elements.
A common best practice is to use a consistent two or three-character prefix for your components. For instance, all Aurelia-provided components start with the prefix au-.
There are various ways to create custom components in Aurelia, from simple convention-based components to more explicit and configurable ones.
The creation process is flexible, allowing you to adopt the approach that best fits your project's needs.
Aurelia treats any exported JavaScript class as a component by default. As such, there's no difference between an Aurelia component and a vanilla JavaScript class at their core.
Here's an example of a basic Aurelia component. You might add logic and bindable properties as needed, but at its simplest, a component is just a class.
export class AppLoader {
// Component logic goes here
}<p>Loading...</p>By convention, Aurelia pairs the app-loader.ts view model with a corresponding app-loader.html file.
Embrace Conventions
Using Aurelia's conventions offers several benefits:
Reduced boilerplate code.
Cleaner and more portable codebases.
Enhanced code readability and learnability.
Less setup and ongoing maintenance.
Smoother upgrades to new versions and different platforms.
The @customElement decorator provides a way to define components, bypassing conventions explicitly.
import { customElement } from 'aurelia';
import template from './app-loader.html';
@customElement({
name: 'app-loader',
template
})
export class AppLoader {
// Component logic goes here
}<p>Loading...</p>The @customElement decorator allows for a variety of customizations, such as defining a different HTML template or inline template string, specifying the element's tag name, and configuring other component properties that would otherwise be managed by Aurelia.
Here's an example of defining the template inline:
import { customElement } from 'aurelia';
@customElement({
name: 'app-loader',
template: '<p>Loading...</p>'
})
export class AppLoader {
// Component logic goes here
}This approach is useful for simple components that don't require a separate view file.
The @customElement decorator allows for several configuration options:
This option sets the HTML tag name for the component. For instance, specifying "app-loader" means the component can be used in views as <app-loader></app-loader>.
If you only need to set the name, you can use a simpler syntax:
import { customElement } from 'aurelia';
@customElement('app-loader')
export class AppLoader {
// Component logic goes here
}The template option allows you to define the content of your component's template. You can specify an external template file, an inline template string, or even set it to null for components that don't require a view:
import { customElement } from 'aurelia';
@customElement({
name: 'app-loader',
template: null
})
export class AppLoader {
// Component logic goes here
}Omitting the template property means Aurelia won't use conventions to locate the template.
You can declare explicit dependencies within the @customElement decorator, which can be an explicit way to manage dependencies without using the <import> tag in your templates:
import { customElement } from 'aurelia';
import { NumberInput } from './number-input';
@customElement({
name: 'app-loader',
dependencies: [NumberInput]
})
export class AppLoader {
// Component logic goes here
}Aurelia provides an API for creating components programmatically, which is especially useful for testing.
import { CustomElement } from '@aurelia/runtime-html';
export class App {
MyField = CustomElement.define({
name: 'my-input',
template: '<input value.bind="value">'
});
// Application logic goes here
}The CustomElement.define method allows for a syntax similar to the @customElement decorator, including dependencies and other configurations.
While it's useful to know about this API, it's typically unnecessary to define custom elements within Aurelia applications. This method is more relevant for writing tests, which you can learn about here.
It's possible to create components in Aurelia using only HTML without a corresponding view model.
For instance, an HTML-only loader component might look like this:
<p>Loading...</p>To use this component, import and reference it:
<import from="./app-loader.html"></import>
<app-loader></app-loader>You can create HTML components with bindable properties using the <bindable> custom element, which serves a similar purpose to the @bindable decorator in a view model:
<bindable name="loading"></bindable>
<p>${loading ? 'Loading...' : ''}</p>Here's how you would use it:
<import from="./app-loader.html"></import>
<app-loader loading.bind="isLoading"></app-loader>Though less common, there are times when you might need a component with a view model but no view. Aurelia allows for this with the @customElement decorator by omitting the template property.
For example, a loading indicator using the nprogress library might be implemented as follows:
import nprogress from 'nprogress';
import { bindable, customElement } from 'aurelia';
import 'nprogress/nprogress.css';
@customElement({
name: 'loading-indicator',
template: null // No view template
})
export class LoadingIndicator {
@bindable loading = false;
loadingChanged(newValue) {
if (newValue) {
nprogress.start();
} else {
nprogress.done();
}
}
}In this example, nprogress manages the DOM manipulation, so a template isn't necessary.
To use your custom components, you must register them either globally or within the scope of their intended use.
Register a component globally in main.ts using the .register method:
import Aurelia from 'aurelia';
import { MyApp } from './my-app';
import { SomeElement } from './path-to/some-element';
Aurelia
.register(SomeElement)
.app(MyApp)
.start();To use a component within a specific template, import it using the <import> tag:
<import from="./path-to/some-element"></import>To use a component but with an alias, import it using the <import> tag, together with the as attribute for the new name:
<import from="./path-to/some-element" as="the-element"></import>To use alias for a specific resource on an import, using the <import> tag, together with the {name}.as attribute for the new name, with {name} being the resource name:
<import from="./path-to/some-element" my-element.as="the-element"></import>Sometimes you may want to render a component without its enclosing tags, effectively making it "containerless."
Be cautious when using containerless components, as you lose the ability to reference the element's container tags, which can complicate interactions with third-party libraries or testing. Use containerless only when necessary.
Mark a component as containerless with the containerless property:
import { customElement, ICustomElementViewModel } from 'aurelia';
@customElement({
name: 'my-component',
containerless: true
})
export class MyComponent implements ICustomElementViewModel {
// Component logic goes here
}The @containerless decorator is an alternative way to indicate a containerless component:
import { ICustomElementViewModel } from 'aurelia';
import { containerless } from '@aurelia/runtime-html';
@containerless
export class MyComponent implements ICustomElementViewModel {
// Component logic goes here
}When using <my-component></my-component>, Aurelia will remove the surrounding tags, leaving only the inner content.
Declare a containerless component inside a view using the <containerless> tag:
<containerless>
<!-- Custom element markup goes here -->
</containerless>Not to be confused with the task queue in Aurelia 1, the TaskQueue in Aurelia is an advanced scheduler designed to handle synchronous and asynchronous tasks efficiently. It provides a robust solution to common issues like timing problems, memory leaks, and race conditions often arising from traditional JavaScript timing functions like setTimeout, setInterval, and unmanaged promises.
Improved Performance: By managing tasks more efficiently, the TaskQueue enhances the performance of applications.
Synchronous and Asynchronous Support: It supports both synchronous and asynchronous tasks, providing greater flexibility in handling tasks.
Deterministic Task Execution: Facilitates testing by providing deterministic ways to wait for task completion, reducing test flakiness.
Avoids Common Pitfalls: Helps avoid common issues associated with setTimeout and setInterval, such as memory leaks and race conditions.
setTimeout (Synchronous)Instead of `setTimeout, ' the TaskQueue offers a more reliable way to queue tasks without delay.
import { PLATFORM } from 'aurelia';
const task = PLATFORM.taskQueue.queueTask(() => {
// Task to be executed after the delay
doStuff();
}, { delay: 100 });
// Cancel the task if needed
task.cancel();If you were to use a native setTimout, it would look like this:
// Queue
const handle = setTimeout(() => {
doStuff();
}, 100);
// Cancel
clearTimeout(handle);setTimeout*Testability: You can await PLATFORM.taskQueue.yield() or use PLATFORM.taskQueue.flush() in tests for predictable task execution.
Improved Reliability: Reduces the chances of intermittent and hard-to-debug failures.
For asynchronous operations, the TaskQueue can handle tasks without the issues of floating promises.
import { PLATFORM } from 'aurelia';
const task = PLATFORM.taskQueue.queueTask(async () => {
await doAsyncStuff();
}, { delay: 100 });
// Await the result of the task
await task.result;
// Cancel if necessary
task.cancel();The TaskQueue can mimic setInterval functionality, offering more control and reliability.
import { PLATFORM } from 'aurelia';
const task = PLATFORM.taskQueue.queueTask(() => {
// Repeated task
poll();
}, { delay: 100, persistent: true });
// Cancel the repeating task
task.cancel();For tasks that need to synchronize with the browser's repaint, domWriteQueue is a safer alternative to requestAnimationFrame.
import { PLATFORM } from 'aurelia';
PLATFORM.domWriteQueue.queueTask(() => {
// Update styles or DOM
applyStyles();
});For continuous animations, the TaskQueue can be used to create a loop, similar to requestAnimationFrame.
import { PLATFORM } from 'aurelia';
const task = PLATFORM.domWriteQueue.queueTask(() => {
// Update animation properties in each frame
updateAnimationProps();
}, { persistent: true });
// Stop the animation
task.cancel();Value converters in Aurelia 2 are an essential feature that allows you to create custom logic to transform data for display in your views. When it comes to testing value converters, you should aim for a mix of unit and integration tests to ensure that they function correctly both in isolation and when integrated within a view.
Let's start with a simple value converter that transforms a string to uppercase:
import { valueConverter } from 'aurelia';
@valueConverter('toUpper')
export class ToUpper {
toView(value: string): string {
return value ? value.toUpperCase() : value;
}
}This value converter checks if the input is a string and, if so, transforms it to uppercase. If the input is null or undefined, it simply returns the input without modification.
When testing value converters, we will create unit tests to validate the converter logic and integration tests to ensure the converter works as expected within an Aurelia view.
Before writing tests, make sure to set up the test environment as described in the Overview Section.
Create a test file for your value converter, such as to-uppercase.spec.ts. Here we will write tests for both unit and integration scenarios.
import { createFixture } from '@aurelia/testing';
import { ToUpper } from './to-upper';
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';
describe('ToUpper value converter', () => {
let sut: ToUpper;
beforeAll(() => {
// Initialize the test environment before running the tests
bootstrapTestEnvironment();
sut = new ToUpper();
});
// Unit Tests
it('returns null for null input', () => {
expect(sut.toView(null)).toBeNull();
});
it('transforms provided string to uppercase', () => {
expect(sut.toView('rOb wAs hErE')).toBe('ROB WAS HERE');
});
it('transforms provided string containing numbers to uppercase', () => {
expect(sut.toView('rob is here 123')).toBe('ROB IS HERE 123');
});
// Integration Test
it('works within a view', async () => {
const { appHost, startPromise, tearDown } = createFixture(
'<div>${text | toUpper}</div>',
class App {
text = 'rob is here 123';
},
[ToUpper]
);
await startPromise;
expect(appHost.textContent).toBe('ROB IS HERE 123');
await tearDown();
expect(appHost.textContent).toBe('');
});
});In the unit tests, we instantiate the ToUpper value converter and directly call its toView method with different inputs to verify the output. We test with null, a valid string, and a string with numbers to cover various scenarios.
The integration test uses the createFixture function to test the value converter within an Aurelia view. We define a mock component with a text property bound to the view and apply the toUpper value converter. We then assert that the rendered text content is transformed as expected.
This method of testing can be applied to any class-based code in Aurelia 2. While the fixture bootstrap functionality is excellent for testing component output and behavior, it's not always necessary for unit testing pure code logic.
Testing value converters is an essential step in ensuring the reliability and robustness of your Aurelia 2 applications. By writing both unit and integration tests, you can confidently verify that your value converters perform correctly in isolation and within the context of an Aurelia view.
Learn how to work with Aurelia's observable decorator to create reactive properties inside your component view models that have change callbacks.
Unlike the @watch decorator, the @observable decorator allows you to decorate properties in a component and optionally call a change callback when the value changes. It works quite similarly to the @bindable property.
By convention, the change handler is a method whose name is composed of the property_name and the literal value 'Changed'. For example, if you decorate the property color with @observable, you have to define a method named colorChanged() to be the change handler.
This is what a basic observable would look like using conventions:
import { observable } from 'aurelia';
export class Car {
@observable color = 'blue';
colorChanged(newValue, oldValue) {
// this will fire whenever the 'color' property changes
}
}When the color value is changed, the colorChanged callback will be fired. The new changed value will be the first argument, and the existing one will be the second one.
If you prefer, you can also put the @observable decorator on classes:
import { observable } from 'aurelia';
@observable('color')
@observable({ name: 'speed', callback: 'speedCallback' })
export class Car {
color = 'blue';
speed = 300;
colorChanged(newValue, oldValue) {
// this will fire whenever the 'color' property changes
}
speedCallback(newValue, oldValue) {
// this will fire whenever the 'speed' property changes
}
}If you do not want to use the convention, you can define the callback name for the change handler by setting the callback property of the @observable decorator:
import { observable } from 'aurelia';
export class Car {
@observable({ callback: 'myCallback' }) color = 'blue';
myCallback(newValue, oldValue) {
// this will fire whenever the 'color' property changes
}
}<h1>${someValue | toLowercase}</h1>export class ToLowercaseValueConverter {
toView(value) {
return value.toLowerCase();
}
}<h1>${someValue | toLowercase | bold }</h1><h1>${someValue | date:'en-UK'}<h1>${someValue | date:format}export class MyApp {
format = 'en-US';
}<ul>
<li repeat.for="user of users | sort: { propertyName: 'age', direction: 'descending' }">${user.name}</li>
</ul>export class ThingValueConverter {
toView(value) {
return value;
}
}import { valueConverter } from 'aurelia';
@valueConverter('date')
export class FormatDate {
toView(value: string, locale = 'en-US') {
const date = new Date(value);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
const format = Intl.DateTimeFormat(locale, {
month: 'long',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC'
});
if (Number.isNaN(date.valueOf())) {
return 'Invalid Date';
}
return format.format(date);
}
}<import from="./date-value-converter" /><p>${'2021-06-22T09:21:26.699Z' | date}</p><p>${'2021-06-22T09:21:26.699Z' | date:'en-GB'}</p>import { valueConverter } from 'aurelia';
@valueConverter('currencyFormat')
export class CurrencyFormatValueConverter {
toView(value, locale = 'en-US', currency = 'USD') {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(value);
}
}<p>Total: ${amount | currencyFormat:'en-US':'USD'}</p>import { valueConverter } from 'aurelia';
@valueConverter('emoji')
export class EmojiConverter {
private emojiMap = {
"love": "❤️", "happy": "😊", "sad": "😢",
"angry": "😠", "coffee": "☕", "star": "⭐",
"cat": "🐱", "dog": "🐶", "pizza": "🍕"
};
toView(value: string) {
return value.split(/\s+/).map(word =>
this.emojiMap[word.toLowerCase()] || word
).join(' ');
}
}<p>${'I love coffee and pizza' | emoji}</p>import { valueConverter } from 'aurelia';
@valueConverter('leetSpeak')
export class LeetSpeakConverter {
toView(value: string) {
return value.replace(/a/gi, '4').replace(/e/gi, '3').replace(/l/gi, '1').replace(/t/gi, '7');
}
}<p>${'Aurelia is elite!' | leetSpeak}</p>import { valueConverter } from 'aurelia';
@valueConverter('upsideDown')
export class UpsideDownConverter {
private flipMap = {
'a': 'ɐ', 'b': 'q', 'c': 'ɔ', 'd': 'p', 'e': 'ǝ',
'f': 'ɟ', 'g': 'ƃ', 'h': 'ɥ', 'i': 'ᴉ', 'j': 'ɾ',
'k': 'ʞ', 'l': 'l', 'm': 'ɯ', 'n': 'u', 'o': 'o',
'p': 'd', 'q': 'b', 'r': 'ɹ', 's': 's', 't': 'ʇ',
'u': 'n', 'v': 'ʌ', 'w': 'ʍ', 'x': 'x', 'y': 'ʎ',
'z': 'z', 'A': '∀', 'B': '𐐒', 'C': 'Ɔ', 'D': 'ᗡ',
'E': 'Ǝ', 'F': 'Ⅎ', 'G': '⅁', 'H': 'H', 'I': 'I',
'J': 'ſ', 'K': 'Ʞ', 'L': '˥', 'M': 'W', 'N': 'N',
'O': 'O', 'P': 'Ԁ', 'Q': 'Q', 'R': 'ᴚ', 'S': 'S',
'T': '⊥', 'U': '∩', 'V': 'Λ', 'W': 'M', 'X': 'X',
'Y': '⅄', 'Z': 'Z', '1': 'Ɩ', '2': 'ᄅ', '3': 'Ɛ',
'4': 'ㄣ', '5': 'ϛ', '6': '9', '7': 'ㄥ', '8': '8',
'9': '6', '0': '0', '.': '˙', ',': "'", '?': '¿',
'!': '¡', '"': '„', "'": ',', '`': ',', '(': ')',
')': '(', '[': ']', ']': '[', '{': '}', '}': '{',
'<': '>', '>': '<', '&': '⅋', '_': '‾'
};
toView(value: string) {
return value.split('').map(char =>
this.flipMap[char] || char
).reverse().join('');
}
}<p>${'Hello Aurelia!' | upsideDown}</p>import { valueConverter } from 'aurelia';
@valueConverter('ordinal')
export class OrdinalValueConverter {
toView(value: number) {
const suffixes = ["th", "st", "nd", "rd"];
const v = value % 100;
return value + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
}
}<p>${position | ordinal}</p>import { valueConverter } from 'aurelia';
@valueConverter('morse')
export class MorseCodeValueConverter {
private morseAlphabet = {
"A": ".-", "B": "-...", "C": "-.-.", "D": "-..",
"E": ".", "F": "..-.", "G": "--.", "H": "....",
"I": "..", "J": ".---", "K": "-.-", "L": ".-..",
"M": "--", "N": "-.", "O": "---", "P": ".--.",
"Q": "--.-", "R": ".-.", "S": "...", "T": "-",
"U": "..-", "V": "...-", "W": ".--", "X": "-..-",
"Y": "-.--", "Z": "--..",
"1": ".----", "2": "..---", "3": "...--", "4": "....-",
"5": ".....", "6": "-....", "7": "--...", "8": "---..",
"9": "----.", "0": "-----",
};
toView(value: string) {
return value.toUpperCase().split('').map(char =>
this.morseAlphabet[char] || char
).join(' ');
}
}<p>${message | morse}</p>Learn about how to subscribe to and handle router events.
You can use the lifecycle hooks (instance and shared) to intercept different stages of the navigation when you are working with the routed components directly. However, if you want to tap into different navigation phases from a non-routed component, such as standalone service or a simple custom element, then you need to leverage router events. This section discusses that.
The router emits the following events.
au:router:location-change: Emitted when the browser location is changed via the popstate and hashchange events.
au:router:navigation-start: Emitted by router before executing a routing instruction; or in other words, before performing navigation.
au:router:navigation-end: Emitted when the navigation is completed successfully.
au:router:navigation-cancel: Emitted when the navigation is cancelled via a non-true return value from canLoad or canUnload lifecycle hooks.
au:router:navigation-error: Emitted when the navigation is erred.
The events can be subscribed to using the event aggregator. However, there is another type-safe alternative to that.
To this end, inject the IRouterEvents and use the IRouterEvents#subscribe.
import {
IRouterEvents,
LocationChangeEvent,
NavigationStartEvent,
NavigationEndEvent,
NavigationCancelEvent,
NavigationErrorEvent,
} from '@aurelia/router-lite';
import { IDisposable } from 'aurelia';
export class SomeService implements IDisposable {
private readonly subscriptions: IDisposable[];
public log: string[] = [];
public constructor(@IRouterEvents events: IRouterEvents) {
this.subscriptions = [
events.subscribe('au:router:location-change', (event: LocationChangeEvent) => { /* handle event */ }),
events.subscribe('au:router:navigation-start', (event: NavigationStartEvent) => { /* handle event */ }),
events.subscribe('au:router:navigation-end', (event: NavigationEndEvent) => { /* handle event */ }),
events.subscribe('au:router:navigation-cancel', (event: NavigationCancelEvent) => { /* handle event */ }),
events.subscribe('au:router:navigation-error', (event: NavigationErrorEvent) => { /* handle event */ }),
];
}
public dispose(): void {
const subscriptions = this.subscriptions;
this.subscriptions.length = 0;
const len = subscriptions.length;
for (let i = 0; i < len; i++) {
subscriptions[i].dispose();
}
}
}Note that the event-data for every event has a different type. When you are using TypeScript, using IRouterEvents correctly types the event-data to the corresponding event type and naturally provides you with intellisense. This type information won't be available if you subscribe to the events using the event aggregator.
The following example demonstrates the usage of router events, where the root component displays a spinner at the start of navigation, and removes it when the navigation ends.
import { IRouterEvents } from '@aurelia/router-lite';
export class MyApp {
private navigating: boolean = false;
public constructor(@IRouterEvents events: IRouterEvents) {
events.subscribe(
'au:router:navigation-start',
() => (this.navigating = true)
);
events.subscribe(
'au:router:navigation-end',
() => (this.navigating = false)
);
}
}This is shown in action below.
Learn all there is to know about creating routes in Aurelia.
The router takes your routing instructions and matches the URL to determine what components to render. When the URL patch matches the configured route path, the component is loaded in the case of configured routes.
To register routes, you can either use the @route decorator or the static routes property static routes to register one or more routes in your application.
The routing syntax used in the Aurelia router is similar to that of other routers you might have worked with before. The syntax will be very familiar if you have worked with Express.js routing.
A route is an object containing a few required properties that tell the router what component to render, what URL it should match and other route-specific configuration options.
At a minimum, a route must contain path and component properties, or path and redirectTo properties. The component and redirectTo properties can be used in place of one another, allowing you to create routes that point to other routes.
The path property on a route is where you'll spend the most time configuring your routes. The path tells the router what to match in the URL, what parameters there are and if they're required.
A path can be made up of either a static string with no additional values or an array of strings. An empty path value is interpreted as the default route, and only one should be specified.
Named required parameters that are prefixed with a colon. :productId when used in a path, a named required parameter might look like this:
This named parameter is denoted by the colon prefix and is called productId which we will be able to access within our routed component.
Named optional parameters. Like required parameters, they are prefixed with a colon but end with a question mark.
In the above example, we have an optional parameter called variation. We know it's optional because of the question mark at the end. This means it would still be valid if you visited this route with supplying the variation parameter.
Using optional name parameters is convenient for routes where different things can happen depending on the presence of those optional parameters.
Wildcard parameters. Unlike required and optional parameters, wildcard parameters are not prefixed with a colon, instead using an asterisk. The asterisk works as a catch-all, capturing everything provided after it.
In the above code example, we can have an endless path after which it is supplied as a value to the canLoad and load methods.
Besides the basics of path and component a route can have additional configuration options.
id — The unique ID for this route
redirectTo — Allows you to specify whether this route redirects to another route. If the redirectTo path starts with / it is considered absolute, otherwise relative to the parent path.
caseSensitive — Determines whether the path should be case sensitive. By default, this is false
transitionPlan — How to behave when this component is scheduled to be loaded again in the same viewport. Valid values for transitionPlan are:
replace — completely removes the current component and creates a new one, behaving as if the component changed.
invoke-lifecycles — calls canUnload, canLoad, unload and load (default if only the parameters have changed)
none — does nothing (default if nothing has changed for the viewport)
title — Specify a title for the route. This can be a string, or it can be a function that returns a string.
viewport — The name of the viewport this component should be loaded into.
data — Any custom data that should be accessible to matched components or hooks. This is where you can specify data such as roles and other permissions.
routes — The child routes that can be navigated from this route.
By specifying the redirectTo property on our route, we can create route aliases. These allow us to redirect to other routes. We redirect our default route to the products page in the following example.
When creating routes, it is important to note that the component property can do more than accept inline import statements. You can also import the component and specify the component class as the component property if you prefer.
If you are working with the Aurelia application generated using npx makes aurelia you would already have a my-app.ts file to place your routes in. It's the main component of the scaffolded Aurelia application.
As you will learn towards the end of this section, inline import statements allow you to implement lazy-loaded routes (which might be needed as your application grows in size).
If you have a lot of routes, the static property might be preferable from a cleanliness perspective.
The syntax for routes stays the same using the decorator. Just how they have defined changes slightly.
As your application grows, child routes can become a valuable way to organize your routes and keep things manageable. Instead of defining all your routes top-level, you can create routes inside your child components to keep them contained.
An example of where child routes might be useful in creating a dashboard area for authenticated users.
We add a route in our top-level my-app.ts component where we added routes in our previous examples. Now, we will create the dashboard-page component.
You will notice we create routes the same way we learned further above. However, we are defining these inside a component we use for our dashboard section. Notice how we use the au-viewport element inside of the dashboard-page component.
Lastly, let's create our default dashboard component for the landing page.
Now, we can contain all dashboard-specific routes inside of our dashboard-page component for dashboard views. Furthermore, it allows us to implement route guards to prevent unauthorized users from visiting the dashboard.
When a user attempts to visit a route that does not exist, we want to catch this route attempt using a catch-all route. We can use a wildcard * to create a route that does this.
When using a catch-all wildcard route, ensure that it is the last route in your routes array, so it does not hijack any other valid route first.
A good use of a catch-all route might be to redirect users away to a landing page. For example, if you had an online store, you might redirect users to a products page.
You can also specify a component that gets loaded like a normal route:
Most modern bundlers like Webpack support lazy bundling and loading of Javascript code. The Aurelia router allows you to create routes that are lazily loaded only when they are evaluated. What this allows us to do is keep the initial page load bundle size down, only loading code when it is needed.
By specifying an arrow function that returns an inline import we are telling the bundler that our route is to be lazily loaded when requested.
Inline import statements are a relatively new feature. Inside your tsconfig.json file, ensure your module property is set to esnext to support inline import statements using this syntax.
We went over creating routes with support for parameters in the creating routes section, but there is an additional property you can specify on a route called data, , which allows you to associate metadata with a route.
This data property will be available in the routable component and can be a great place to store data associated with a route, such as roles and auth permissions. In some instances, the route parameters can be used to pass data, but for other use cases, you should use the data property.
A common scenario is styling an active router link with styling to signify that the link is active, such as making the text bold. When a route is active, by default, a CSS class name of active will be added to the route element.
In your HTML, if you were to create some links with load attributes and visit one of those routes, the active class would be applied to the link for styling. In the following example, visiting the about route would put class="active" onto our a element.
Aurelia comes with a powerful fully-featured router without the need to install any additional dependencies. If you are new to Aurelia, we recommend visiting the Getting Started section first to familiarise you with the framework.
You are here because you want to familiarize yourself with the router, so we'll make this quick. At the end of this tutorial, you will be familiar with all the concepts and APIs you need to add routing into your Aurelia applications.
While building our recipe application, we will cover the following:
How to create and configure routes
Navigating with load in your views as well as view-models
Styling active links
Programmatically navigating using router APIs
Working with route parameters
A working demo and code for the following tutorial can also be found .
To do this tutorial, you'll need a working Aurelia application. We highly recommend following the guide to scaffold an application. However, for this tutorial, we have a ready to go that we recommend. It will allow you to follow along and live code.
As you will see, it's a boring application with no routing or anything exciting. All it says is Recipes (hardly a recipe application).
The viewport is where our loaded routes are dynamically loaded into. When we click on a route, the <au-viewport> element will be populated with the requested component.
Open my-app.html and add in the <au-viewport> and some navigation links.
This won't do anything just yet because we haven't enabled routing or created any routes.
Let's go into main.ts and configure Aurelia to use routing. Import the RouterConfiguration object and pass it to Aurelia's register method.
We also configure the router to use push-state routing instead of the hash-based router. This gives us cleaner URLs.
Now that we have a viewport and the router enabled let's create some routes. We will start by adding our routes to our root my-app.ts component.
The important thing to note here is that we are not specifying a component to load for these routes. We will do that shortly, but the routing structure is what we are creating here.
The first route has an empty path , which means it's a default route (the router will load this first if no other route is requested). The second route recipes tells the router when the user visits /recipes to load our recipes component. Lastly, the recipes/:recipeId route has a route parameter that allows us to load specific recipes.
We now need to create three components for our routes: the homepage, recipes page, and recipe detail page.
Unlike other frameworks and libraries, Aurelia works on the premise of a view-and-view model. If you familiarize yourself with the Getting Started section, you would already be familiar with these concepts.
Let's create the homepage first:
Let's create the recipes page:
Let's create the recipe detail page:
Lastly, let's import our components in my-app.ts for the routes to load them.
In a non-tutorial application, you would have your API and server providing this data. But, for our tutorial will use a public recipe API instead. We could use mock data, but it would be a lot of data for a recipe application.
The MealDB is a fantastic free meal API that can give us recipes. We will use the to get this data, which wraps up the native Fetch API.
In recipes-page.ts add the following to the component view model:
We've loaded the recipes. Now it's time to display them. Open recipes-page.html and add in the following:
We use Aurelia's repeat.for functionality to loop over the recipes. But take notice of the link with load attribute. Aurelia Router sees this and knows this is a route. We are providing the recipe detail route with the ID of the recipe.
It's not pretty, but we now have a list of recipes.
Sometimes a user might attempt to visit a recipe or page that doesn't exist. You might want to redirect the user or display a 404 page in those situations.
Let's create another component and call it fourohfour-page
We then specify on our <au-viewport> what our fallback is. We need to import this 404 component to use it.
When we created our routes in my-app.ts you might recall we created a recipe detail route which had a recipeId parameter. Now, we are going to modify our recipe-detail component to read this value from the URL and load the content.
There is a little more to unpack here. We inject the router because we will programmatically redirect away if the user attempts to view a non-existent recipe ID. We use the canLoad method because loading our recipe view relies on existing recipes. If the recipe can't be found using the API, we redirect to the recipes page programmatically using the router.load method.
Inside recipe-detail.html we'll render our recipe:
The API we use returns ingredients on a line-by-line basis, so we've omitted those from this example. Now, you should be able to run your application and click on recipes to view them. A headline, image and instructions should now be visible.
As an additional step, you could add those in yourself.
The router automatically adds a active class to all route links when they are active. Because our routes all live in my-app We will edit my-app.css We don't even have to import it (Aurelia does that automatically for us).
The active class is now bold when active. We also do some quick styling tweaks to the route links to remove the underline and make them black so we can see the bold stand out more.
You just built a recipe application. It doesn't allow you to create recipes, and it's not very pretty, but it works. To see the application in action, a working demo of the above code (or below).
{
path: 'my-route',
component: import('./my-component')
}import { IRouteableComponent, IRoute } from '@aurelia/router';
export class MyApp implements IRouteableComponent {
static routes: IRoute[] = [
{
path: 'product/:productId',
component: import('./components/product-detail')
}
]
}import { IRouteableComponent, IRoute } from '@aurelia/router';
export class MyApp implements IRouteableComponent {
static routes: IRoute[] = [
{
path: 'product/:productId/:variation?',
component: import('./components/product-detail')
}
]
}import { IRouteableComponent, IRoute } from '@aurelia/router';
export class MyApp implements IRouteableComponent {
static routes: IRoute[] = [
{
path: 'files/*path',
component: import('./components/files-manager')
}
]
}@routes([
{ path: '', redirectTo: 'products' },
{ path: 'products', component: import('./products'), title: 'Products' },
{ path: 'product/:id', component: import('./product'), title: 'Product' }
])
export class MyApp {
}import { IRouteableComponent, IRoute } from '@aurelia/router';
import { HomePage } from './components/home-page';
export class MyApp implements IRouteableComponent {
static routes: IRoute[] = [
{
path: ['', 'home'],
component: HomePage,
title: 'Home',
}
]
}import { IRouteableComponent, IRoute } from '@aurelia/router';
export class MyApp implements IRouteableComponent {
static routes: IRoute[] = [
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
}
]
}import { IRouteableComponent, routes } from '@aurelia/router';
@routes([
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
}
])
export class MyApp implements IRouteableComponent {
}export class MyApp {
static routes = [
{
path: '/dashboard',
component: () => import('./dashboard-page'),
title: 'Dashboard'
}
];
}import { DashboardHome } from './dashboard-home';
import { IRouteableComponent } from '@aurelia/router';
export class DashboardPage implements IRouteableComponent {
static routes = [
{
path: '',
component: DashboardHome,
title: 'Landing'
}
];
}<div>
<au-viewport></au-viewport>
</div>export class DashboardHome {
}<h1>Dashboard</h1>
<p>Welcome to your dashboard.</p>{
path: '*',
redirectTo: '/products'
}{
path: '*',
component: () => import('./not-found')
} {
path: 'product/:productId',
component: () => import('./components/product-detail')
}@routes([
{
id: 'home',
path: '',
component: import('./home'),
title: 'Home'
},
{
path: 'product/:id',
component: import('./product'),
title: 'Product',
data: {
requiresAuth: false
}
}
])
export class MyApp {
}.active {
font-weight: bold;
}<a load="about">About</a>
<a load="home">Home</a>Styling components using CSS, CSS pre and post-processors as well as working with web components.
Aurelia 2 simplifies the process of styling components, supporting a variety of CSS flavors and encapsulation methods. Whether you prefer raw CSS, PostCSS, SASS, or Stylus, Aurelia 2 streamlines their integration into your components. Ultimately, all styles compile into standard CSS that browsers can interpret.
Aurelia 2 automatically imports styles for custom elements based on file naming conventions. For instance, if you have a custom element named my-component, Aurelia 2 looks for a corresponding stylesheet named my-component.css.
Consider the following file structure:
my-component.ts: The TypeScript file defining the MyComponent class.
my-component.css: The stylesheet containing styles for MyComponent.
my-component.html: The HTML template for MyComponent.
Aurelia 2's convention-based approach eliminates the need to explicitly import the CSS file. When you run your application, Aurelia 2 automatically detects and applies the styles.
export class MyComponent {
// Component logic goes here
}.my-class {
color: blue;
background-color: lightgrey;
padding: 10px;
border-radius: 5px;
}<template>
<p class="my-class">Stylized content here!</p>
</template>When MyComponent is used in the application, the associated styles are automatically applied, giving the paragraph text a blue color and a light grey background with padding and rounded corners.
The Shadow DOM API, part of the Web Components standard, provides encapsulation by hiding the component's internal DOM and styles from the rest of the application. Aurelia 2 offers several options for working with Shadow DOM:
Global Shadow DOM: By default, encapsulates all components in your application.
Configured Shadow DOM: Use the useShadowDOM decorator to opt-in per component.
Global opt-out Shadow DOM: Enable Shadow DOM globally but disable it for specific components.
To enable Shadow DOM after the initial setup, configure it in the main.ts file:
import Aurelia, { StyleConfiguration } from 'aurelia';
import { MyApp } from './my-app';
Aurelia
.register(StyleConfiguration.shadowDOM({
// Configuration options here
}))
.app(MyApp)
.start();The StyleConfiguration class from Aurelia allows you to specify how styles are applied, including options for Shadow DOM.
When using Webpack, ensure the following rule is included in the Webpack configuration:
{
test: /[/\\]src[/\\].+\.html$/i,
use: {
loader: '@aurelia/webpack-loader',
options: {
defaultShadowOptions: { mode: 'open' }
}
},
exclude: /node_modules/
}This rule ensures that HTML files within your src directory are processed correctly to work with Shadow DOM.
In the Shadow DOM, styles are scoped to their components and don't leak to the global scope. To apply global styles across all components, use the sharedStyles property in the Shadow DOM configuration.
import Aurelia, { StyleConfiguration } from 'aurelia';
import { MyApp } from './my-app';
import bootstrap from 'bootstrap/dist/css/bootstrap.css';
Aurelia
.register(StyleConfiguration.shadowDOM({
sharedStyles: [bootstrap] // Apply Bootstrap styles to all components
}))
.app(MyApp)
.start();The sharedStyles property accepts an array, allowing you to include multiple shared stylesheets.
useShadowDOMThe useShadowDOM decorator, imported from Aurelia, lets you enable Shadow DOM on a per-component basis. Without configuration options, it defaults to open mode.
import { useShadowDOM } from 'aurelia';
@useShadowDOM()
export class MyComponent {
// Component logic with Shadow DOM enabled
}You can specify the Shadow DOM mode (open or closed) as a configuration option. The open mode allows JavaScript to access the component's DOM through the shadowRoot property, while closed mode restricts this access.
import { useShadowDOM } from 'aurelia';
@useShadowDOM({ mode: 'closed' })
export class MyComponent {
// Component logic with Shadow DOM in 'closed' mode
}The useShadowDOM decorator also allows disabling Shadow DOM for a specific component by passing false.
import { useShadowDOM } from 'aurelia';
@useShadowDOM(false)
export class MyComponent {
// Component logic without Shadow DOM
}Shadow DOM introduces special selectors that offer additional styling capabilities. These selectors are part of the CSS Scoping Module specification.
The :host selector targets the custom element itself, not its children. You can use the :host() function to apply styles based on the host element's classes or attributes.
:host {
display: block;
border: 1px solid #000;
}
:host(.active) {
background-color: #f0f0f0;
}In this example, all app-header elements have a solid border, and those with the active class have a grey background.
The :host-context selector styles the custom element based on its context within the document.
:host-context(.dark-mode) {
color: white;
background-color: #333;
}Here, app-header elements will have white text on a dark background inside an element with the dark-mode class.
When Shadow DOM does not meet your needs, CSS Modules balance style encapsulation and global accessibility. CSS Modules transform class names into unique identifiers, preventing style collisions.
To use CSS Modules, include the following loader configuration in your Webpack setup:
{
test: /\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true
}
}
],
exclude: /node_modules/
}This rule processes CSS files, enabling CSS module functionality.
Define your styles, and reference the class names in your HTML templates. Webpack will handle the conversion to unique class names.
.title {
font-size: 24px;
color: #333;
}<template>
<h1 class="title">Hello, Aurelia!</h1>
</template>After processing, the title class may be transformed to a unique identifier like title_1a2b3c.
CSS Modules support the :global selector for styling global elements without transformation.
:global(.button-primary) {
background-color: #007bff;
color: white;
}This style will apply globally to elements with the button-primary class, maintaining the class name without transformation.
Shadow DOM encapsulates a component's styles, preventing them from leaking into the global scope. Aurelia 2 offers granular control over Shadow DOM usage, including global and per-component configuration.
When using Shadow DOM, you can style content passed into slots using the ::slotted() pseudo-element.
::slotted(.tab-content) {
padding: 15px;
border: 1px solid #ddd;
}<template>
<slot name="tab-content"></slot>
</template>In this example, content assigned to the tab-content slot will receive padding and a border. At the same time, the encapsulation ensures that these styles don't affect other elements outside the tab-panel component.
CSS variables can be used within Shadow DOM to create themeable components:
:host {
--button-bg-color: #eee;
--button-text-color: #333;
}
button {
background-color: var(--button-bg-color);
color: var(--button-text-color);
}<template>
<button><slot></slot></button>
</template>Users of the button-group component can then define these variables at a higher level to theme the buttons consistently across the application.
Animations can be defined within Shadow DOM to ensure they are scoped to the component:
@keyframes slide-in {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.banner {
animation: slide-in 1s ease-out forwards;
}<template>
<div class="banner">Welcome to Aurelia!</div>
</template>The slide-in animation is encapsulated within the animated-banner component, preventing it from conflicting with any other animations defined in the global scope.
CSS Modules provide a powerful way to locally scope class names, avoiding global conflicts. With Aurelia 2, you can leverage CSS Modules to create maintainable, conflict-free styles.
CSS Modules support composing classes from other modules, promoting reusability.
.baseButton {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.primaryButton {
composes: baseButton;
background-color: #007bff;
color: white;
}<template>
<button class="primaryButton">Click Me</button>
</template>In this example, primaryButton composes the baseButton styles, adding its own background and text color. CSS Modules ensures that these class names are unique to avoid styling conflicts.
CSS Modules can also facilitate theming by exporting and importing variables.
:export {
primaryColor: #007bff;
secondaryColor: #6c757d;
}@value primaryColor, secondaryColor from "./theme.css";
.primaryButton {
background-color: primaryColor;
color: white;
}
.secondaryButton {
background-color: secondaryColor;
color: white;
}<template>
<button class="primaryButton">Primary</button>
<button class="secondaryButton">Secondary</button>
</template>By defining and exporting theme variables in theme.css, they can be imported and used in other CSS Modules to ensure consistent theming across the application.
For more guidance on class and style bindings in Aurelia applications, please take a look at the [CSS classes and styling section](.. templates/class-and-style-bindings.md). This section covers strategies for dynamically working with classes and inline styles.
<div>
<h1>Recipes</h1>
<nav>
<a load="/">Home</a>
<a load="/recipes">Recipes</a>
</nav>
<au-viewport></au-viewport>
</div>import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
import { MyApp } from './my-app';
Aurelia
.register(RouterConfiguration.customize({ useUrlFragmentHash: false }))
.app(MyApp)
.start();export class MyApp {
static routes = [
{
path: '',
component: '',
title: 'Home',
},
{
path: 'recipes',
component: '',
title: 'Recipes',
},
{
path: 'recipes/:recipeId',
component: '',
title: 'Recipe',
},
];
}export class HomePage {
}<p>Welcome to flavortown. Aurelia Recipes is the only recipe application you will need to manage your recipes.</p>export class RecipesPage {
}<p>Your recipes. In one place.</p>export class RecipeDetail {
}<p>This is a recipe.</p>import { HomePage } from './home-page';
import { RecipesPage } from './recipes-page';
import { RecipeDetail } from './recipe-detail';
export class MyApp {
static routes = [
{
path: '',
component: HomePage,
title: 'Home',
},
{
path: '/recipes',
component: RecipesPage,
title: 'Recipes',
},
{
path: '/recipes/:recipeId',
component: RecipeDetail,
title: 'Recipe',
},
];
}import { HttpClient } from '@aurelia/fetch-client';
export class RecipesPage {
private http: HttpClient = new HttpClient();
private recipes = [];
async bound() {
const response = await this.http.fetch(`https://www.themealdb.com/api/json/v1/1/search.php?f=b`);
const result = await response.json();
this.recipes = result.meals;
}
}<ul>
<li repeat.for="recipe of recipes"><a load="/recipes/${recipe.idMeal}">${recipe.strMeal}</a></li>
</ul>export class 404Page {
}<h1>Oops!</h1>
<p>Sorry, that link doesn't exist.</p><import from="./fourohfour-page"></import>
<div>
<h1>Recipes</h1>
<nav>
<a load="/">Home</a>
<a load="/recipes">Recipes</a>
</nav>
<au-viewport fallback="fourohfour-page"></au-viewport>
</divimport { HttpClient } from '@aurelia/fetch-client';
import { IRouter } from '@aurelia/router';
export class RecipeDetail {
private http: HttpClient = new HttpClient();
private recipe;
constructor(@IRouter readonly router: IRouter) {}
async canLoad(parameters) {
if (parameters?.recipeId) {
const loadRecipe = await this.loadRecipe(parameters.recipeId);
if (loadRecipe) {
this.recipe = loadRecipe;
return true;
} else {
this.router.load(`/recipes`);
}
}
}
async loadRecipe(recipeId) {
const request = await this.http.fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${recipeId}`
);
const response = await request.json();
return response.meals ? response.meals[0] : false;
}
}<h1>${recipe.strMeal}</h1>
<img src.bind="recipe.strMealThumb" />
<p textcontent.bind="recipe.strInstructions"></p>.active {
font-weight: bold;
}
a {
color: #000;
text-decoration: none;
}Learn about the different routing hooks and how to leverage those in terms of dis/allow loading or unloading as well as performing setup and teardown of a view.
Inside your routable components which implement the IRouteViewModel interface, there are certain methods that are called at different points of the routing lifecycle. These lifecycle hooks allow you to run code inside of your components such as fetch data or change the UI itself.
If you are working with components you are rendering, implementing IRouteViewModel will ensure that your code editor provides you with intellisense to make working with these lifecycle hooks in the appropriate way a lot easier.
import {
IRouteViewModel,
Params,
RouteNode,
NavigationInstruction,
} from '@aurelia/router-lite';
export class MyComponent implements IRouteViewModel {
canLoad?(
params: Params,
next: RouteNode,
current: RouteNode | null
): boolean
| NavigationInstruction
| NavigationInstruction[]
| Promise<boolean | NavigationInstruction | NavigationInstruction[]>;
loading?(params: Params, next: RouteNode, current: RouteNode | null): void | Promise<void>;
canUnload?(next: RouteNode | null, current: RouteNode): boolean | Promise<boolean>;
unloading?(next: RouteNode | null, current: RouteNode): void | Promise<void>;
}Using the canLoad and canUnload hooks you can determine whether to allow or disallow navigation to and from a route respectively. The loading and unloading hooks are meant to be used for performing setup and clean up activities respectively for a view. Note that all of these hooks can return a promise, which will be awaited by the router-lite pipeline. These hooks are discussed in details in the following section.
canLoadThe canLoad method is called upon attempting to load the component. It allows you to determine if the component should be loaded or not. If your component relies on some precondition being fulfilled before being allowed to render, this is the method you would use.
The component would be loaded if true (it has to be boolean true ) is returned from this method. To disallow loading the component you can return false. You can also return a navigation instruction to navigate the user to a different view. These are discussed in the following sections.
Returning any value other than boolean true, from within the canLoad function will cancel the router navigation.
The following example shows that a parameterized route, such as /c1/:id?, can only be loaded if the value of id is an even number. Note that the value of the id parameter can be grabbed from the the first argument (params) to the canLoad method.
import { Params } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({
name: 'c-one',
template: `c1 \${id}`,
})
export class ChildOne {
private id: number;
public canLoad(params: Params): boolean {
const id = Number(params.id);
if (!Number.isInteger(id) || id % 2 != 0) return false;
this.id = id;
return true;
}
}You can also see this example in action below.
canLoadNot only can we allow or disallow the component to be loaded, but we can also redirect. The simplest way is to return a string path from canLoad. In the following example, we re-write the previous example, but instead of returning false, we return a path, where the user will be redirected.
import { NavigationInstruction, Params } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({
name: 'c-one',
template: `c1 \${id}`,
})
export class ChildOne {
private id: number;
public canLoad(params: Params): boolean | NavigationInstruction {
const id = Number(params.id);
// If the id is not an even number then redirect to c2
if (!Number.isInteger(id) || id % 2 != 0) return `c2/${params.id}`;
this.id = id;
return true;
}
}You can also see this example in action below.
If you prefer a more structured navigation instructions then you can also do so. Following is the same example using route-id and parameters object.
import { NavigationInstruction, Params } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({
name: 'c-one',
template: `c1 \${id}`,
})
export class ChildOne {
private id: number;
public canLoad(params: Params): boolean | NavigationInstruction {
const id = Number(params.id);
if (!Number.isInteger(id) || id % 2 != 0)
return { component: 'r2', params: { id: params.id } };
this.id = id;
return true;
}
}Note that you can also choose to return a sibling navigation instructions. This can be done by returning an array of navigation instructions.
import { NavigationInstruction, Params } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
import { Workaround } from './workaround';
@customElement({
name: 'c-one',
template: `c1 \${id}`,
})
export class ChildOne {
private id: number;
public canLoad(params: Params): boolean | NavigationInstruction {
const id = Number(params.id);
if (!Number.isInteger(id) || id % 2 != 0)
return [
{ component: Workaround },
{ component: 'r2', params: { id: params.id } },
];
this.id = id;
return true;
}
}You can also see the example in action below.
Apart from accessing the route parameter, the query and the fragment associated with the URL can also be accessed inside the canLoad hook. To this end, you can use the second argument (next) to this method.
The following example shows that id query parameter is checked whether that is an even number or not. If that condition does not hold, then user is redirected to a different view with the query and fragment.
import { NavigationInstruction, Params, RouteNode } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({
name: 'c-one',
template: `c1 \${id} fragment: \${fragment}`,
})
export class ChildOne {
private id: number;
private fragment: string;
public canLoad(
params: Params,
next: RouteNode
): boolean | NavigationInstruction {
this.fragment = next.fragment;
const query = next.queryParams;
const rawId = query.get('id');
const redirectPath = `c2?${next.queryParams.toString()}${
next.fragment ? `#${next.fragment}` : ''
}`;
if (rawId === null) return redirectPath;
const id = Number(rawId);
if (!Number.isInteger(id) || id % 2 != 0) return redirectPath;
this.id = id;
return true;
}
}You can also see the example in action below.
loadingThe loading method is called when your component is navigated to. If your route has any parameters supplied, they will be provided to the loading method as an object with one or more parameters as the first argument.
In many ways, the loading method is the same as canLoad with the exception that loading cannot prevent the component from loading. Where canLoad can be used to redirect users away from the component, the loading method cannot.
This lifecycle hook can be utilized to perform setup; for example, fetching data from backend API etc.
All of the above code examples for canLoad can be used with load and will work the same with the exception of being able to return true or false boolean values to prevent the component being loaded.
One of the examples is refactored using loading hook that is shown below.
Following is an additional example, that shows that you can use the next.title property to dynamically set the route title from the loading hook.
import { IRouteViewModel, Params, RouteNode } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({
name: 'c-one',
template: `c1 \${msg}`,
})
export class ChildOne implements IRouteViewModel {
private msg: string;
public loading(params: Params, next: RouteNode) {
this.msg = `loaded with id: ${params.id}`;
next.title = 'Child One';
}
}canUnloadThe canUnload method is called when a user attempts to leave a routed view. The first argument (next) of this hook is a RouteNode which provides information about the next route.
This hook is like the canLoad method but inverse. You can return a boolean true from this method, allowing the router-lite to navigate away from the current component. Returning any other value from this method will disallow the router-lite to unload this component.
Returning any value other than boolean true, from within the canUnload function will cancel the router navigation.
The following example shows that before navigating away, the user is shown a confirmation prompt. If the user agrees to navigate way, then the navigation is performed. The navigation is cancelled, if the user does not confirm.
import { IRouteViewModel, Params, RouteNode } from '@aurelia/router-lite';
import { IPlatform } from '@aurelia/runtime-html';
export class ChildOne implements IRouteViewModel {
public constructor(@IPlatform private readonly platform: IPlatform) {}
public canUnload(next: RouteNode, current: RouteNode): boolean {
const from = current.computeAbsolutePath();
const to = next.computeAbsolutePath();
return this.platform.window.confirm(
`Do you want to navigate from '${from}' to '${to}'?`
);
}
}You can see this example in action below.
unloadingThe unloading hook is called when the user navigates away from the current component. The first argument (next) of this hook is a RouteNode which provides information about the next route.
This hook is like the loading method but inverse.
The following example shows that a unloading hook logs the event of unloading the component.
public unloading(next: RouteNode): void {
this.logger.log(
`unloading for the next route: ${next.computeAbsolutePath()}`
);
}This can also be seen in the live example below.
For completeness it needs to be noted that the canLoad hook is invoked before loading and canUnload hook is invoked before unloading. In the context of swapping two views/components it is as follows.
canUnload hook (when present) of the current component is invoked.
canLoad hook (when present) of the next component (assuming that the canUnload returned true) is invoked.
unloading hook (when present) of the current component is invoked.
loading hook (when present) of the current component is invoked.
Note that the last 2 steps may run in parallel, if the hooks are asynchronous.
Aurelia 2 enhances the handling of promises within templates. Unlike Aurelia 1, where promises had to be resolved in the view model before passing their values to templates, Aurelia 2 allows direct interaction with promises in templates. This is achieved through the promise.bind template controller, which supports then, pending, and catch states, reducing the need for boilerplate code.
The promise.bind template controller allows you to use then, pending and catch in your view, removing unnecessary boilerplate.
The promise binding simplifies working with asynchronous data. It allows attributes to bind to various states of a promise: pending, resolved, and rejected.
<div promise.bind="promise1">
<template pending>The promise is not yet settled.</template>
<template then="data">The promise is resolved with ${data}.</template>
<template catch="err">This promise is rejected with ${err.message}.</template>
</div>
<div promise.bind="promise2">
<template pending>The promise is not yet settled.</template>
<template then>The promise is resolved.</template>
<template catch>This promise is rejected.</template>
</div>The following example demonstrates a method fetchAdvice bound to the promise.bind attribute. It uses then and catch to handle resolved data and errors.
<let i.bind="0"></let>
<div promise.bind="fetchAdvice(i)">
<span pending>Fetching advice...</span>
<span then="data">
Advice id: ${data.slip.id}<br>
${data.slip.advice}
<button click.trigger="i = i+1">try again</button>
</span>
<span catch="err">
Cannot get advice, error: ${err}
<button click.trigger="i = i+1">try again</button>
</span>
</div>export class MyApp {
fetchAdvice() {
return fetch(
"https://api.adviceslip.com/advice",
{
// This is not directly related to promise template controller.
// This is simply to ensure that the example demonstrates the
// change in data in every browser, without any confusion.
cache: 'no-store'
}
)
.then(r => r.ok
? r.json()
: (() => { throw new Error('Unable to fetch NASA APOD data') })
)
}
}This example can also be seen in action below.
The promise template controller operates within its own scope, preventing accidental pollution of the parent scope or view model.
<div promise.bind="promise">
<foo-bar then="data" foo-data.bind="data"></foo-bar>
<fizz-buzz catch="err" fizz-err.bind="err"></fizz-buzz>
</div>In this example, data and err are scoped within the promise controller. To access these values in the view model, use $parent.data or $parent.err.
Aurelia 2 supports nested promise bindings, allowing you to handle promises returned by other promises.
<template promise.bind="fetchPromise">
<template pending>Fetching...</template>
<template then="response" promise.bind="response.json()">
<template then="data">${data}</template>
<template catch>Deserialization error</template>
</template>
<template catch="err2">Cannot fetch</template>
</template>When using promise.bind within a repeat.for, it's recommended to use a let binding to create a scoped context.
<let items.bind="[[42, true], ['foo-bar', false], ['forty-two', true], ['fizz-bazz', false]]"></let>
<template repeat.for="item of items">
<template promise.bind="item[0] | promisify:item[1]">
<let data.bind="null" err.bind="null"></let>
<span then="data">${data}</span>
<span catch="err">${err.message}</span>
</template>
</template>import { valueConverter } from '@aurelia/runtime-html';
@valueConverter('promisify')
class Promisify {
public toView(value: unknown, resolve: boolean = true): Promise<unknown> {
return resolve ? Promise.resolve(value) : Promise.reject(new Error(String(value)));
}
}The above example shows usage involving repeat.for chained with a promisify value converter. Depending on the second boolean value, the value converter converts a simple value to a resolving or rejecting promise. The value converter in itself is not that important for this discussion. It is used to construct a repeat.for, promise combination easily.
The important thing to note here is the usage of let binding that forces the creation of two properties, namely data and err, in the overriding context, which gets higher precedence while binding.
Without these properties in the overriding context, the properties get created in the binding context, which eventually gets overwritten with the second iteration of the repeat. In short, with let binding in place, the output looks as follows.
<span>42</span>
<span>foo-bar</span>
<span>forty-two</span>
<span>fizz-bazz</span>Creating injectable services is crucial for building maintainable applications in Aurelia. Services encapsulate shared functionalities such as business logic or data access, and can be easily injected where needed. This guide will demonstrate various methods for creating injectable services, including the use of DI.createInterface() and directly exporting classes.
DI.createInterface() to Create Injectable ServicesDI.createInterface() allows you to create an injection token that can be used with a default implementation:
Here, ILoggerService is both an injection token and a type representing the LoggerService class. This simplifies the process as you won't need to manually define an interface with all the methods of the LoggerService.
You can also create an interface token without a default implementation for more flexibility:
In this scenario, you must register the implementation with the DI container:
For services that don't require an interface, simply exporting a class is sufficient:
This service can be auto-registered or manually registered:
Aurelia supports decorators for controlling service registration:
The @singleton() decorator ensures a single instance of AuthService within the DI container.
Sometimes, you may want to export a type equal to the class, which can serve as an interface. This approach reduces redundancy and keeps the service definition concise:
You can then use this type for injection and for defining the shape of your service without having to declare all methods explicitly:
Aurelia provides multiple approaches to creating and registering injectable services, including DI.createInterface() and directly exporting classes or types. By choosing the method that best fits your needs, you can achieve a clean and flexible architecture with easily injectable services, promoting code reuse and separation of concerns across your application.
A developer guide that details numerous strategies for implementing animation into Aurelia applications.
Learn numerous techniques for implementing animations into your Aurelia applications.
In instances where you don't need to implement router-based transition animations (entering and leaving), we can lean on traditional CSS-based animations to add animation to our Aurelia applications.
Let's animate the disabled state of a button by making it wiggle when we click on it:
Some animations are reactive based on user input or other application actions. An example might be a mousemove event changing the background colour of an element.
In this example, when the user moves their mouse over the DIV, we get the clientX value and feed it to a reactive style string that uses the x value to complete the HSL color value. We use lower percentages for the other values to keep the background dark for our white text.
Not to be confused with state animations, a reactive animation is where we respond to changes in our view models instead of views and animate accordingly. You might use an animation library or custom animation code in these instances.
In the following example, we will use the animation engine Anime.js to animate numeric values when a slider input is changed. Using the change event on our range slider, we'll animate the number up and down depending on the dragged value.
import { DI } from 'aurelia';
export class LoggerService {
log(message: string) {
console.log(message);
}
}
export const ILoggerService = DI.createInterface<ILoggerService>('ILoggerService', x => x.singleton(LoggerService));
// Export type equal to the class to create an interface
export type ILoggerService = LoggerService;import { DI } from 'aurelia';
export class LoggerService {
log(message: string) {
// Logging logic
}
}
// Export type equal to the class to create an interface
export type ILoggerService = LoggerService;
export const ILoggerService = DI.createInterface<ILoggerService>('ILoggerService');import { Registration } from 'aurelia';
container.register(
Registration.singleton(ILoggerService, LoggerService)
);export class AuthService {
isAuthenticated(): boolean {
// Authentication logic
return true;
}
}import { Registration } from 'aurelia';
container.register(
Registration.singleton(AuthService, AuthService)
);import { singleton } from 'aurelia';
@singleton()
export class AuthService {
isAuthenticated(): boolean {
// Authentication logic
return true;
}
}export class PaymentProcessor {
processPayment(amount: number) {
// Payment processing logic
}
}
// Export type equal to the class to create an interface
export type IPaymentProcessor = PaymentProcessor;import { inject } from 'aurelia';
@inject()
export class CheckoutService {
constructor(private paymentProcessor: IPaymentProcessor) {
// Use paymentProcessor
}
}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.
A component that is loaded as part of a route definition. The IRouteableComponent
import { IRouteableComponent } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
}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.
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
}
}As outlined in the Creating Routes section, routes can be specified using the routes decorator or the static routes property.
export class MyApp {
static routes = [
{
path: '/products',
component: () => import('./products-page'),
title: 'Products'
}
];
}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'
}
];
}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'
}
}
];
}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'
}
];
}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);
}
}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';
}
}Resolvers in Aurelia 2 are integral to the Dependency Injection (DI) system, providing various strategies for resolving dependencies. This guide will cover each resolver type, its usage, and when to use it, with detailed code examples for both the @inject decorator and static inject property methods. Additionally, we will discuss how to create custom resolvers.
Aurelia 2 offers several built-in resolvers to address different dependency resolution needs. Here's how to use them with both the @inject decorator and static inject property.
lazy ResolverUse the lazy resolver when you want to defer the creation of a service until it's needed. This is particularly useful for expensive resources.
@inject Decoratorimport { lazy, inject } from 'aurelia';
@inject(lazy(MyService))
export class MyClass {
constructor(private getMyService: () => MyService) {
// Call getMyService() when you need an instance of MyService
}
}inject Propertyimport { lazy } from 'aurelia';
export class MyClass {
static inject = [lazy(MyService)];
constructor(private getMyService: () => MyService) {
// Similar usage as with the decorator
}
}all ResolverThe all resolver is used to inject an array of all instances registered under a particular key. This is useful when working with multiple implementations of an interface.
@inject Decoratorimport { all, inject } from 'aurelia';
@inject(all(MyService))
export class MyClass {
constructor(private services: MyService[]) {
// services is an array of MyService instances
}
}inject Propertyimport { all } from 'aurelia';
export class MyClass {
static inject = [all(MyService)];
constructor(private services: MyService[]) {
// Similar usage as with the decorator
}
}optional ResolverThe optional resolver allows a service to be injected if available, or undefined if not. This can prevent runtime errors when a dependency is not critical.
@inject Decoratorimport { optional, inject } from 'aurelia';
@inject(optional(MyService))
export class MyClass {
constructor(private service?: MyService) {
// service is MyService or undefined
}
}inject Propertyimport { optional } from 'aurelia';
export class MyClass {
static inject = [optional(MyService)];
constructor(private service?: MyService) {
// Similar usage as with the decorator
}
}factory ResolverThe factory resolver provides a function to create instances of a service, allowing for more control over the instantiation process.
@inject Decoratorimport { factory, inject } from 'aurelia';
@inject(factory(MyService))
export class MyClass {
constructor(private createMyService: () => MyService) {
// createMyService is a function to create MyService instances
}
}inject Propertyimport { factory } from 'aurelia';
export class MyClass {
static inject = [factory(MyService)];
constructor(private createMyService: () => MyService) {
// Similar usage as with the decorator
}
}newInstanceForScope ResolverUse newInstanceForScope when you need a unique instance of a service within a particular scope, such as a component or sub-container.
@inject Decoratorimport { newInstanceForScope, inject } from 'aurelia';
@inject(newInstanceForScope(MyService))
export class MyClass {
constructor(private service: MyService) {
// service is a new scoped instance of MyService
}
}inject Propertyimport { newInstanceForScope } from 'aurelia';
export class MyClass {
static inject = [newInstanceForScope(MyService)];
constructor(private service: MyService) {
// Similar usage as with the decorator
}
}newInstanceOf ResolverThe newInstanceOf resolver ensures that a fresh instance of a service is created each time, regardless of other registrations.
@inject Decoratorimport { newInstanceOf, inject } from 'aurelia';
@inject(newInstanceOf(MyService))
export class MyClass {
constructor(private service: MyService) {
// service is a fresh instance of MyService
}
}inject Propertyimport { newInstanceOf } from 'aurelia';
export class MyClass {
static inject = [newInstanceOf(MyService)];
constructor(private service: MyService) {
// Similar usage as with the decorator
}
}You can create custom resolvers by implementing the IResolver interface. Custom resolvers give you the flexibility to implement complex resolution logic that may not be covered by the built-in resolvers.
import { IResolver, IContainer, inject } from 'aurelia';
class MyCustomResolver<T> implements IResolver {
$isResolver: true;
constructor(private key: new (...args: any[]) => T) {}
resolve(handler: IContainer, requestor: IContainer): T {
// Custom resolution logic here
return new this.key();
}
}
// Usage
@inject(new MyCustomResolver(MyService))
export class MyClass {
constructor(private service: MyService) {
// service is resolved using MyCustomResolver
}
}In the example above, MyCustomResolver is a custom resolver that creates a new instance of MyService. You can further customize the resolve method to suit your specific requirements.
By understanding and utilizing these resolvers, you can achieve a high degree of flexibility and control over the dependency injection process in your Aurelia 2 applications. The examples provided illustrate how to apply each resolver using both the @inject decorator and static inject property, giving you the tools to manage dependencies effectively in any situation.
export class MyApp {
private disabled = false;
animateButton() {
this.disabled = true;
setTimeout(() => {
this.disabled = false;
}, 2000);
}
}@keyframes wiggle {
0%, 7% {
transform: rotateZ(0);
}
15% {
transform: rotateZ(-15deg);
}
20% {
transform: rotateZ(10deg);
}
25% {
transform: rotateZ(-10deg);
}
30% {
transform: rotateZ(6deg);
}
35% {
transform: rotateZ(-4deg);
}
40%, 100% {
transform: rotateZ(0);
}
}
.wiggle {
animation: wiggle 2s linear infinite;
}<button type="button" wiggle.class="disabled" click.trigger="animateButton()">Wiggle!</button>export class MyApp {
private x = 0;
mouseMove(x) {
this.x = x;
}
}.movetransition {
padding: 20px;
transition: 0.4s background-color easein-out;
}<div
mousemove.trigger="mouseMove($event.clientX)"
style="background-color: hsl(${x}, 40%, 32%)"
class="movetransition"
>
<p>Move it, move it.</p>
<p>X value is: ${x}</p>
</div>import anime from 'animejs';
export class MyApp {
private sliderVal = 0;
private sliderWrapper: HTMLElement;
animateValue() {
anime({
targets: this.sliderWrapper,
textContent: `${this.sliderVal}`,
easing: 'easeInOutQuad',
round: true,
duration: 1200,
});
}
}<input
type="range"
min="0"
max="1000000"
value.bind="sliderVal"
change.trigger="animateValue()"
/>
<p ref="sliderWrapper" class="slider-wrapper">${sliderVal & oneTime}</p>.slider-wrapper {
background: #333;
color: #fff;
display: block;
font-family: Arial, Helvetica, sans-serif;
font-size: 19px;
font-weight: bold;
padding: 12px;
}Aurelia makes it easy to create your own plugins. Learn how you can create individual plugins, register them and work with tasks to run code at certain parts of the lifecycle process.
One of the most important needs of users is to design custom plugins. In the following, we want to get acquainted with how to design a plugin in the form of a mono-repository structure with configuration.
A monorepo (mono repository) is a single repository that stores all of your code and assets for every project. Using a monorepo is important for many reasons. It creates a single source of truth. It makes it easier to share code. It even makes it easier to refactor code.
With workspaces. Workspaces are a set of features in the npm CLI that offer support for managing multiple packages within a single top-level, root package. NPM v7 has shipped with Node.js v15.
To move forward with a practical example. We want to implement Bootstrap components in a custom mono-repository with a configuration to make it customizable.
We want to separate our plugin into three packages.
bootstrap-v5-core
We will add the Bootstrap 5 configurations to this package.
bootstrap-v5
Our Bootstrap 5 components will define in this package. bootstrap-v5 depends on bootstrap-v5-core packages.
demo
We will use our plugin in this package as a demo. demo depends on bootstrap-v5-core and bootstrap-v5.
To configure your monorepo, you should do as following:
Make sure you have installed NPM v7+
npm -vGo to a folder that you want to make the project, for example my-plugin
Create a packages folder and package.json inside it.
// package.json content
{
"name": "@my-plugin",
"workspaces": [
"packages/**"
]
}The mono repository's name is @my-plugin. We defined our workspaces (projects) under packages folder.
Open your packages folder and install the projects inside it.
npx makes aurelia bootstrap-v5-core -s typescript
npx makes aurelia bootstrap-v5 -s typescript
npx makes aurelia demo -s typescriptAfter creating, delete all files inside src folders of bootstrap-v5-core and bootstrap-v5 but resource.d.ts. We will add our files there.
As described in the structure section defined packages depend on each other. So, we link them together and add the other prerequisites for each. At the same time it is good to name them a bit better.
bootstrap-v5-core
Go to its package.json and change the name to
"name": "@my-plugin/bootstrap-v5-core"As our core package, it has no dependency.
bootstrap-v5
Go to its package.json and change the name to
"name": "@my-plugin/bootstrap-v5"Then, add the following dependencies:
// bootstrap-v5/package.json
"dependencies": {
"aurelia": "latest",
"bootstrap": "^5.0.0-beta2",
"@my-plugin/bootstrap-v5-core": "0.1.0"
},demo
Go to its package.json and change the name to
"name": "@my-plugin/demo"Then, add the following dependencies:
// demo/package.json
"dependencies": {
"aurelia": "latest",
"@my-plugin/bootstrap-v5-core": "0.1.0",
"@my-plugin/bootstrap-v5": "0.1.0"
},Note: All created packages have 0.1.0 version so pay attention if the version changes, update it correctly.
Run the command below to install packages inside the my-plugin folder.
npm installGo to the src folder of bootstrap-v5-core package and create each of the below files there.
Size
As I mentioned before, I want to write a configurable Bootstrap plugin so create src/Size.ts file.
// Size.ts
export enum Size {
ExtraSmall = 'xs',
Small = 'sm',
Medium = 'md',
Large = 'lg',
ExtraLarge = 'xl',
}I made a Size enum to handle all Bootstrap sizes. I want to make an option for those who use the plugin to define a global size for all Bootstrap components at first. Next, we manage our components according to size value.
Bootstrap 5 Options
Create src/BootstrapV5Options.ts file.
// BootstrapV5Options.ts
import { Size } from "./Size";
export interface IBootstrapV5Options {
defaultSize?: Size;
}
const defaultOptions: IBootstrapV5Options = {
defaultSize: Size.Medium
};You need to define your configurations via an interface with its default values as a constant.
DI
To register it via DI, you need to add codes below too:
// BootstrapV5Options.ts
import { IContainer } from '@aurelia/kernel';
import { AppTask, DI, Registration } from 'aurelia';
function configure(container: IContainer, config: IBootstrapV5Options = defaultOptions) {
return container.register(
AppTask.hydrating(IContainer, async container => {
if (config.enableSpecificOption) {
const file = await import('file');
cfg.register(Registration.instance(ISpecificOption, file.do());
}
Registration.instance(IBootstrapV5Options, config).register(container);
})
);
}
export const IBootstrapV5Options = DI.createInterface<IBootstrapV5Options>('IBootstrapV5Options');
export const BootstrapV5Configuration = {
register(container: IContainer) {
return configure(container);
},
customize(config: IBootstrapV5Options) {
return {
register(container: IContainer) {
return configure(container, config);
},
};
}
};configure helps us to set the initial options or loading special files based on a specific option to DI system. To load specific files, you need to do this via AppTask.
The AppTask allows you to position when/where certain initialization should happen and also optionally block app rendering accordingly.
If you no need this feature replace it with:
function configure(container: IContainer, config: IBootstrapV5Options = defaultOptions) {
Registration.instance(IBootstrapV5Options, config).register(container);
}Registration.instance helps us to register our default option into the container.
To use your option later inside your components, you should introduce it via DI.createInterface. The trick here is to create a resource name the same as what you want to inject. This is the reason I name it as IBootstrapV5Options constant.
Finally, you need to make sure that the user can determine the settings. This is the task of BootstrapV5Configuration.
register This method helps the user to use your plugin with default settings but customize is the method that allows the user to introduce their custom settings.
Exports
Create src/index.ts file.
// index.ts
export * from './BootstrapV5Configuration';
export * from './Size';Create new index.ts file inside bootstrap-v5-core package too.
export * from './src';Go to the src folder of bootstrap-v5 package, create a button folder then create each of the below files there.
View
Create bs-button.html file.
<button class="btn btn-primary btn-${size}" ref="bsButtonTemplate">
Primary Button
</button>ViewModel
Create bs-button.ts file.
import { customElement, containerless, BindingMode, bindable } from "aurelia";
import template from "./bs-button.html";
import { IBootstrapV5Options, Size } from "@my-plugin/bootstrap-v5-core";
@customElement({ name: "bs-button", template })
@containerless
export class BootstrapButton {
private bsButtonTemplate: Element;
@bindable({ mode: BindingMode.toView }) public size?: Size = null;
constructor(
@IBootstrapV5Options private options: IBootstrapV5Options
) {
}
attached() {
this.applySize();
}
private applySize() {
if (this.options.defaultSize && !this.size) {
switch (this.options.defaultSize) {
case Size.ExtraSmall:
case Size.Small:
this.resetSize();
this.size = Size.Small;
break;
case Size.Large:
case Size.ExtraLarge:
this.resetSize();
this.size = Size.Large;
break;
default:
this.resetSize();
this.size = Size.Medium;
}
}
}
private resetSize() {
this.bsButtonTemplate.classList.remove("btn-sm", "btn-lg");
}
}As you can see we are able to access to plugin options easy via ctor (DI) and react appropriately to its values.
@IBootstrapV5Options private options: IBootstrapV5OptionsIn this example, I get the size from the user and apply it to the button component. If the user does not define a value, the default value will be used.
Exports
Create files below correctly:
Create src/button/index.ts file.
export * from './bs-button';Create src/index.ts file.
export * from './button';Create new index.ts file inside bootstrap-v5 package.
import 'bootstrap/dist/css/bootstrap.min.css';
export * from './src';Open demo package and go to the src and update main.ts.
// main.ts
import Aurelia from 'aurelia';
import { MyApp } from './my-app';
import { BootstrapV5Configuration } from '@my-plugin/bootstrap-v5-core';
import * as BsComponents from '@my-plugin/bootstrap-v5';
Aurelia
.register(BsComponents, BootstrapV5Configuration)
.app(MyApp)
.start();Importing is available for whole components
import * as BsComponents from '@my-plugin/bootstrap-v5';Or just a component
import { BootstrapButton } from '@my-plugin/bootstrap-v5';To register your components you should add them to register method.
.register(BsComponents) // For whole components
// Or
.register(BootstrapButton) // For a componentWe support configuration so we should introduce it to register method too.
// With default options
.register(BootstrapV5Configuration)
// Or with a custom option
.register(BootstrapV5Configuration.customize({
defaultSize: Size.Small // Components loads with small size.
}))Now, You are able to use your bs-button inside src/my-app.html.
<bs-button></bs-button>
<bs-button size="lg"></bs-button>To run the demo easily, go to the my-plugin root folder and add the following script section to the package.json.
{
"name": "@my-plugin",
"workspaces": [
"packages/**"
],
"scripts": {
"start": "npm run --prefix packages/demo start"
}
}Then, call the command
npm run start
npm startLearn about configuring the Router-Lite.
The router allows you to configure how it interprets and handles routing in your Aurelia applications. The customize method on the RouterConfiguration object can be used to configure router settings.
useUrlFragmentHashIf you do not provide any configuration value, the default is pushState routing. If you prefer hash-based routing to be used, you can enable this like so:
By calling the customize method, you can supply a configuration object containing the property useUrlFragmentHash and supplying a boolean value. If you supply true this will enable hash mode. The default is false.
If you are working with pushState routing, you will need a <base> element with href attribute (for more information, refer ) in the head of your document. The scaffolded application from the CLI includes this in the index.html file, but if you're starting from scratch or building within an existing application you need to be aware of this.
basePathConfiguring a base path is useful in many real-life scenarios. One such example is when you are hosting multiple smaller application under a single hosting service. In this case, you probably want the URLs to look like https://example.com/app1/view42 or https://example.com/app2/view21. In such cases, it is useful to specify a different value for every app.
Run the following example to understand how the value defined in base#href is affecting the URLs.
When you open the example in a new browser tab, you can note that the URL in the address bar looks the HOSTING_PREFIX/app/home or HOSTING_PREFIX/app/about. This is also true for the href values in the a tags. This happens because <base href="/app"> is used in the index.ejs (producing the index.html). In this case, the router-lite is picking up the baseURI information and performing the routing accordingly.
This needs bit more work when you are supporting multi-tenancy for your app. In this case, you might want the URLs look like https://example.com/tenant-foo/app1/view42 or https://example.com/tenant-bar/app2/view21. You cannot set the document.baseURI every time you start the app for a different tenant, as that value is static and readonly, read from the base#href value.
With router-lite you can support this by setting the basePath value differently for each tenant, while customizing the router configuration, at bootstrapping phase. Following is an example that implements the aforementioned URL convention. To better understand, open the the example in a new tab and check the URL in address bar when you switch tenants as well as the links in the a tags.
The actual configuration takes place in the main.ts while customizing the router configuration in the following lines of code.
There are also the following links, included in the my-app.html, to simulate tenant switch/selection.
Note the a tags with . Note that when you switch to a tenant, the links in the a tags also now includes the tenant name; for example when we switch to tenant 'foo' the 'Home' link is changed to /foo/app/home from /app/home.
A buildTitle function can be used to customize the . For this example, we assume that we have the configured the routes as follows:
With this route configuration in place, when we navigate to /home, the default-built title will be Home | Aurelia. We can use the following buildTitle function that will cause the title to be Aurelia - Home when users navigate to / or /home route.
Check out the following live example. You might need to open the demo in a new tab to observe the title changes.
Translating the title
When localizing your app, you would also like to translate the title. Note that the router does not facilitate the translation by itself. However, there are enough hooks that can be leveraged to translate the title. To this end, we would use the in the route configuration to store the i18n key.
As data is an object of type Record<string, unknown>, you are free to chose the property names inside the data object. Here we are using the i18n property to store the i18n key for individual routes.
In the next step we make use of the buildTitle customization as well as a AppTask hook to subscribe to the locale change event.
This customization in conjunction with the previously shown routing configuration will cause the title to be Aurelia - Startseite when user is navigated to / or /home route and the current locale is de. Here we are assuming that the i18n resource for the de locale contains the following.
The following example demonstrate the title translation.
href custom attribute using useHrefBy default, the router will allow you to use both href as well as load for specifying routes. Where this can get you into trouble is external links, mailto: links and other types of links that do not route. A simple example looks like this:
This seemingly innocent and common scenario by default will trigger the router and will cause an error.
You have two options when it comes to working with external links. You can specify the link as external using the .
Or, you can set useHref to false (default is true) and only ever use the load attribute for routes.
Using the historyStrategy configuration option it can be instructed, how the router-lite should interact with the browser history object. This configuration option can take the following values: push, replace, and none.
pushThis is the default strategy. In this mode, the router-lite will interact with Browser history to push a new navigation state each time a new navigation is performed. This enables the end users to use the back and forward buttons of the browser to navigate back and forth in an application using the router-lite.
Check out the following example to see this in action.
The main configuration can be found in the main.ts.
To demonstrate the push behavior, there is a small piece of code in the my-app.ts that listens to router events to create informative text (the history property in the class) from the browser history object that is used in the view to display the information.
As you click the Home and About links in the example, you can see that the new states are being pushed to the history, and thereby increasing the length of the history.
replaceThis can be used to replace the current state in the history. Check out the following example to see this in action. Note that the following example is identical with the previous example, with the difference of using the replace-value as the history strategy.
As you interact with this example, you can see that new states are replacing old states, and therefore, unlike the previous example, you don't observe any change in the length of the history.
noneUse this if you don't want the router-lite to interact with the history at all. Check out the following example to see this in action. Note that the following example is identical with the previous example, with the difference of using the none-value as the history strategy.
As you interact with this example, you can see that there is absolutely no change in the history information, indicating non-interaction with the history object.
You can use the to override the configured history strategy for individual routing instructions.
Using the activeClass option you can add a class name to the router configuration. This class name is used by the when the associated instruction is active. The default value for this option is null, which also means that the load custom attribute won't add any class proactively. Note that the router-lite does not define any CSS class out-of-the-box. If you want to use this feature, make sure that you defines the class as well in your stylesheet.
The routing lifecycle allows you to run code at different points of the routing lifecycle such as fetching data or changing the UI.
Inside your routable components which implement the IRouteableComponent interface, certain methods are called at different points of the routing lifecycle. These lifecycle hooks allow you to run code inside of your components, such as fetching data or changing the UI itself.
If you are working with components you are rendering, implementing IRouteableComponent will ensure that your code editor provides you with intellisense to make working with these lifecycle hooks easier.
The canLoad method is called upon attempting to load the component. If your route has any parameters supplied, they will be provided to the canLoad method as an object with one or more parameters as the first argument.
The canLoad method allows you to determine if the component should be loaded or not. If your component relies on data being present from the API or other requirements being fulfilled before being allowed to render, this is the method you would use.
When working with the canLoad method, you can use promises to delay loading the view until a promise and/or promises have been resolved. The component would be loaded if we were to return true from this method.
If you wanted to load data from an API, you could make the canLoad method async, which would make it a promise-based method. You would be awaiting an actual API call of some kind in place of ....load data
Unlike other async methods, if the promise does not resolve, the component will not load. The canLoad lifecycle method tells the router if the component is allowed to load. It's a great router method for components that rely on data loading such as product detail or user profile pages.
Not only can we allow or disallow the component to be loaded, but we can also redirect it. If you want to redirect to the root route, return a string with an / inside it. You can return a route ID, route path match or navigation instruction from inside this callback to redirect.
Returning a boolean false, string or RoutingInstruction from within the canLoad function will cancel the router navigation.
The loading method is called when your component is navigated to. If your route has any parameters supplied, they will be provided to the load method as an object with one or more parameters as the first argument.
In many ways, the loading method is the same as canLoad with the exception that loading cannot prevent the component from loading. Where canLoad can be used to redirect users away from the component, the loading method cannot.
All of the above code examples for canLoad can be used with loading and will work the same, with exception of being able to return true or false boolean values to prevent the component being loaded (as we just mentioned).
The canUnload method is called when a user attempts to leave a routed view. The first argument of this callback is a INavigatorInstruction it provides information about the next route. You can return a component, boolean or string value from this method.
Like the canLoad method, this is just the inverse. It determines if we can navigate away from the current component.
The unloading method is called if the user is allowed to leave and is in the process of leaving. The first argument of this callback is a INavigatorInstruction it provides information about the next route.
Like the loading method, this is just the inverse. It is called when the component is unloaded (provided canUnload wasn't false).
A common router scenario is you want to route to a specific component, say a component that displays product information based on the ID in the URL. You request the API to get the information and display it.
Two asynchronous lifecycles are perfect for dealing with loading data: canLoad and load - both supporting returning a promise (or async/await).
If the component you are loading absolutely requires the data to exist on the server and be returned, the canLoad lifecycle method is the best place to do it. Using our example of a product page, if you couldn't load product information, the page would be useful, right?
From the inside canLoad you can redirect the user elsewhere or return false to throw an error.
Similarly, if you still want the view to load, even if we can't get the data, you would use the loadinglifecycle callback.
When you use load and async the component will wait for the data to load before rendering.
If you worked with routing in Aurelia 1, you might be accustomed to a currentInstruction property available on the router. In Aurelia 2, this property does not exist. There are, however, two properties on the router called activeNavigation and activeComponents which can be used to achieve a similar result. You can also reference the instruction itself from within route lifecycle functions.
The activeNavigation property contains quite a few properties but most notably has the current URL path, query parameters and other navigation-specific values. You might want to get information about the current route.
We can get information about the current route by accessing the activeComponents array and determining the active component. Still, it is possible that more than one component will be in this array. An easier way is to get the route instruction on the canLoad and loading lifecycle methods.
It might seem like a mouthful, but to get the current instruction that resulted in the viewport's current content, this is the current approach to take from within those aforementioned methods inside your components.
The parameters object contains a Javascript object of any URL parameters. If your URL contains /?myprop=22&frag=0 then this object would contain {myprop: '22', frag: '0'} , allowing you to get fragment values.
While you would often set the title of a route in your route configuration object using the title property, sometimes you want the ability to specify the title property from within the routed component itself.
You can achieve this from within the canLoad and load methods in your component. By setting the next.title property, you can override or transform the title.
import { IRouteableComponent, Parameters, Navigation, RoutingInstruction } from '@aurelia/router';
export class MyComponent implements IRouteableComponent {
canLoad(params: Parameters, instruction: RoutingInstruction, navigation: Navigation);
loading(params: Parameters, instruction: RoutingInstruction, navigation: Navigation);
canUnload(instruction: RoutingInstruction, navigation: Navigation);
unloading(instruction: RoutingInstruction, navigation: Navigation);
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyProduct implements IRouteableComponent {
canLoad(params: Parameters) {
return true;
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyProduct implements IRouteableComponent {
async canLoad(params: Parameters) {
await ....load data (Fetch call, etc)
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyProduct implements IRouteableComponent {
canLoad(params: Parameters) {
return '/'; // Matches default empty route
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyProduct implements IRouteableComponent {
canLoad(params: Parameters) {
return 'products'; // Matches route with ID 'products'
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyProduct implements IRouteableComponent {
canLoad(params: Parameters) {
return '/products/54'; // Matches route path for product/:productId
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyComponent implements IRouteableComponent {
async canLoad(params: Parameters) {
this.product = await this.api.getProduct(params.productId);
}
}import { IRouteableComponent, Parameters } from "@aurelia/router";
export class MyComponent implements IRouteableComponent {
async loading(params: Parameters) {
this.product = await this.api.getProduct(params.productId);
}
}import { IRouteableComponent, IRouter, Navigation, Parameters, RoutingInstruction } from '@aurelia/router';
loading(parameters: Parameters, instruction: RoutingInstruction, navigation: Navigation): void | Promise<void> {
console.log(instruction.endpoint.instance.getContent().instruction);
}loading() {
console.log(this.router.activeNavigation.parameters);
}import { IRouteableComponent, Parameters, RoutingInstruction, Navigation } from "@aurelia/router";
export class ProductPage implements IRouteableComponent {
loading(parameters: Parameters, instruction: RoutingInstruction, navigation: Navigation) {
instruction.route.match.title = 'COOL BEANS';
}
}
import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router-lite';
Aurelia
.register(RouterConfiguration.customize({ useUrlFragmentHash: true }))
.app(component)
.start();<head>
<base href="/">
</head><!-- app1/index.html -->
<head>
<base href="/app1">
</head>
<!-- app2/index.html -->
<head>
<base href="/app2">
</head> // this can either be '/', '/app[/+]', or '/TENANT_NAME/app[/+]'
let basePath = location.pathname;
const tenant =
(!basePath.startsWith('/app') && basePath != '/'
? basePath.split('/')[1]
: null) ?? 'none';
if (tenant === 'none') {
basePath = '/app';
}
const host = document.querySelector<HTMLElement>('app');
const au = new Aurelia();
au.register(
StandardConfiguration,
RouterConfiguration.customize({
basePath,
}),
Registration.instance(ITenant, tenant) // <-- this is just to inject the tenant name in the `my-app.ts`
);tenant: ${tenant}
<nav>
<a href="${baseUrl}/foo/app" external>Switch to tenant foo</a>
<a href="${baseUrl}/bar/app" external>Switch to tenant bar</a>
</nav>
<nav>
<a load="home">Home</a>
<a load="about">About</a>
</nav>
<au-viewport></au-viewport>
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
import { Home } from './home';
import { About } from './about';
import { DI } from '@aurelia/kernel';
export const ITenant = DI.createInterface<string>('tenant');
@route({
routes: [
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: 'about',
component: About,
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {
private baseUrl = location.origin;
public constructor(@ITenant private readonly tenant: string) {}
}import { route, IRouteViewModel } from '@aurelia/router-lite';
@route({
title: 'Aurelia', // <-- this is the base title
routes: [
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
}
]
})
export class MyApp implements IRouteViewModel {}// main.ts
import { RouterConfiguration, Transition } from '@aurelia/router';
import { Aurelia } from '@aurelia/runtime-html';
const au = new Aurelia();
au.register(
RouterConfiguration.customize({
buildTitle(tr: Transition) {
const root = tr.routeTree.root;
const baseTitle = root.context.config.title;
const titlePart = root.children.map(c => c.title).join(' - ');
return `${baseTitle} - ${titlePart}`;
},
}),
);import { IRouteViewModel, Routeable } from "aurelia";
export class MyApp implements IRouteViewModel {
static title: string = 'Aurelia';
static routes: Routeable[] = [
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
data: {
i18n: 'routes.home'
}
}
];
}import { I18N, Signals } from '@aurelia/i18n';
import { IEventAggregator } from '@aurelia/kernel';
import { IRouter, RouterConfiguration, Transition } from '@aurelia/router';
import { AppTask, Aurelia } from '@aurelia/runtime-html';
(async function () {
const host = document.querySelector<HTMLElement>('app');
const au = new Aurelia();
const container = au.container;
let i18n: I18N | null = null;
let router: IRouter | null = null;
au.register(
// other registrations such as the StandardRegistration, I18NRegistrations come here
RouterConfiguration.customize({
buildTitle(tr: Transition) {
// Use the I18N to translate the titles using the keys from data.i18n.
i18n ??= container.get(I18N);
const root = tr.routeTree.root;
const baseTitle = root.context.config.title;
const child = tr.routeTree.root.children[0];
return `${baseTitle} - ${i18n.tr(child.data.i18n as string)}`;
},
}),
AppTask.afterActivate(IEventAggregator, ea => {
// Ensure that the title changes whenever the locale is changed.
ea.subscribe(Signals.I18N_EA_CHANNEL, () => {
(router ??= container.get(IRouter)).updateTitle();
});
}),
);
// start aurelia here
})().catch(console.error);{
"routes": {
"home": "Startseite"
}
}<a href="mailto:[email protected]">Email Me</a><a href="mailto:[email protected]" external>Email Me</a>import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router-lite';
Aurelia
.register(RouterConfiguration.customize({
useHref: false
}))
.app(component)
.start();import { RouterConfiguration } from '@aurelia/router-lite';
import { Aurelia, StandardConfiguration } from '@aurelia/runtime-html';
import { MyApp as component } from './my-app';
(async function () {
const host = document.querySelector<HTMLElement>('app');
const au = new Aurelia();
au.register(
StandardConfiguration,
RouterConfiguration.customize({
historyStrategy: 'push', // default value can can be omitted
})
);
au.app({ host, component });
await au.start();
})().catch(console.error);import { IHistory } from '@aurelia/runtime-html';
import { IRouterEvents } from '@aurelia/router-lite';
export class MyApp {
private history: string;
public constructor(
@IHistory history: IHistory,
@IRouterEvents events: IRouterEvents
) {
let i = 0;
events.subscribe('au:router:navigation-end', () => {
this.history = `#${++i} - len: ${history.length} - state: ${JSON.stringify(history.state)}`;
});
}
}How to implement router "guards" into your applications to protect routes from direct access.
Router hooks are pieces of code that can be invoked at the different stages of routing lifecycle. In that sense, these hooks are similar to the of the routed view models. The difference is that these hooks are shared among multiple routed view models. Therefore, even though the hook signatures are similar to that of the , these hooks are supplied with an that is the view model instance.
Shared lifecycle hook logic can be defined by implementing one of the router lifecycle hooks (canLoad, loading etc.) on a class with the @lifecycleHooks() decorator. This hook will be invoked for each component where this class is available as a dependency.
While the router hooks are indeed independent of the components you are routing to, the functions are basically the same as you would use inside of an ordinary component.
This is the contract for ordinary route lifecycle hooks for components:
And the following is the contract for shared lifecycle hooks.
The only difference is the addition of the first viewModel parameter. This comes in handy when you need the component instance since the this keyword won't give you access to the component instance like it would in ordinary instance hooks.
Before starting with the involved details of the shared/global lifecycle hooks, let us first create an example lifecycle hook. To this end, we consider the typical use-case of authorization; that is restricting certain routes to users with certain permission claims.
For this example, we will create two lifecycle hooks; one for authentication and another is for authorization. However, before directly dive into that, let us briefly visit, how the routes are configured.
Note that the of the route configuration option is used here to define the routes' permission claim. This is used by the auth hooks later to determine whether to allow or disallow the navigation. With that we are now ready to discuss the hooks.
The first hook will check if the current route is protected by a claim and there is a currently logged in user. When there is no logged in user, it performs a redirect to login page. This is shown below.
The second hook will check if the current user has the permission claims to access the route. Where the user does not satisfies the claims requirements the user is redirected to a forbidden page. This is shown below.
Lastly, we need to register these two hooks to the DI container to bring those into action.
Note that the authentication hook is registered before the authorization hook. This ensures that the authentication hook is invoked before than the authorization hook which is also semantically sensible.
And that's the crux of it. You can see this example in action below.
Note that even though in the example we limit the the hooks to only canLoad method, more than one lifecycle methods/hooks can also be leveraged in a shared lifecycle hook (a class decorated by the @lifecycleHooks() decorator).
The lifecycle hooks can be registered either globally (as it is done in the or as .
The globally registered lifecycle hooks are invoked for every components. Thus, it is recommended to use those sparsely. On the other hand, when a hook is registered as a dependency of a particular component, it is invoked only for that one component.
This is shown in the example below, where there are two globally registered hooks, which are invoked for every components.
Note that the globally registered hooks in the example above do nothing significant other than logging the invocations. This is shown below.
The log entries are then enumerated on the view. The following is one such example of log entries.
You may get a different log depending on your test run. However, it can still be clearly observed that both hook1 and hook2 are invoked for every components. Depending on your use-case, that might not be optimal.
To achieve a granular control on the lifecycle hooks, you can register the hooks as the for individual routed view models. This ensures that the lifecycle hooks are invoked only for the components where those are registered as dependencies. This shown in the example below where there are three hooks, and one component has two hooks registered as dependencies and another component has only hook registered.
When ChildOne or ChildTwo is loaded or unloaded you can observe that only Hook2 is invoked for ChildTwo, whereas both Hook1 and Hook2 are invoked for ChildOne. Below is an example log from one of such test runs.
You can see the example in action below.
You can of course choose to use both kind of registrations. The following example shows that Hook3 is registered globally and therefore is invoked for every components whereas Hook1 is only invoked for ChildOne and Hook2 is only invoked for ChildTwo.
When using multiple lifecycle hooks, if any hook returns a non-true value (either a false or a navigation instruction) from canLoad or canUnload, it preempts invocation of the other hooks in the routing pipeline.
This is shown in the following example. The example shows that there are two hooks, namely hook1 and hook2. hook1 return false if the path c1 is navigated with a non-number and non-even number; for example it denies navigation to c1/43 but allows c1/42.
You can see the example in action below.
If you run the example and try clicking the links, you can observe that once hook1 returns false, hook2 is not invoked. One such example log is shown below.
The thumb rule is that the hooks are invoked in the order they are registered. That is if some Hook1 is registered before Hook2 in DI then Hook1 will be invoked before the Hook2. You can see this in the example of .
That is also true, when registering hooks as one of the dependencies for a custom element. You can see this in the example of .
When using both globally registered hooks as well as local dependencies, the global hooks are invoked before the locally registered hooks. You can see this in action in .
Lastly, the shared lifecycle hooks are invoked before the instance lifecycle hooks.
Learn how to work with the @aurelia/router package to implement routing in your Aurelia applications.
Routing with Aurelia feels like a natural part of the framework. It can easily be implemented into your applications in a way that feels familiar if you have worked with other frameworks and library routers.
This section is broken up into two parts—a quick introduction to the router and router configuration.
Currently, two routers ship with Aurelia: router lite and core router. This section refers to the core router package that lives in @aurelia/router — please see the warning note below on a caveat some developers encounter when working with the router.
Before you go any further: Please ensure you are importing from the @aurelia/router package. Sometimes import extensions will autocomplete your imports and import from the aurelia package, which currently exports the lite router. Eventually, the aurelia package will export the @aurelia/router package, but it currently does not. We have noticed, in many instances, that using the incorrect router imports is why routing is not working.
See how you can configure and implement routing in your Aurelia applications in only a few minutes. Of course, you will want to expand upon this as you build your routes. Here we only learn the bare minimum to get started.
The following getting started guide assumes you have an Aurelia application already created. If not, to get Aurelia installed in minutes.
To use the router, we have to register it with Aurelia. We do this inside of main.ts (or main.js if you're working with Javascript) — the router is then enabled after it is registered. You might already have code like this if you chose the routing example when generating using the Makes scaffolding tool.
Once again, it bears repeating. Please make sure your router imports are being imported from @aurelia/router in your `main.ts` file, but also in other parts of your Aurelia application as well.
Now, we create our routes. We'll do this inside my-app.ts and use the static routes property. Please note that there is also a @routes decorator, which is detailed inside the section.
For our two routes, we import and provide their respective components. Your components are just classes and can be very simple. Here is the HomePage component. Please note that you can use inline imports when creating routes, also detailed in the section.
Take note of the path property which is empty. This tells the router that the HomePage component is our default route. If no route is supplied, it will load this as the default component. The component property is the component that will be loaded (self-explanatory). And the title property is the title for our route.
And the view model for our component is equally simple:
First, let's look at the HTML. If you use the makes tool to scaffold your Aurelia application. This might be my-app.html
load
Notice how we use a standard hyperlink <a> tags, but they have an load attribute instead of href? This attribute tells the router that these are routable links. The router will translate these load values into routes (either path or route name). By default, the router does also allow you to use href for routes (a setting that can be turned off below configuring useHref).
au-viewport
This tells the router where to display your components. It can go anywhere inside your HTML. It can also have a name (handy for instances where there are multiple au-viewport elements), and you can have more than one.
The router allows you to configure how it interprets and handles routing in your Aurelia applications. The customize method on the RouterConfiguration object can be used to set numerous router settings besides the useUrlFragmentHash value.
The title can be set for the overall application. By default, the title uses the following value: ${componentTitles}${appTitleSeparator}Aurelia the component title (taken from the route or component) and the separator, followed by Aurelia.
In most instances, using the above string title is what you will want. You will want the solution below if you need to set the title or transform the title programmatically.
Using the transformTitlemethod from the router customization, the default title-building logic can be overwritten. This allows you to set the title programmatically, perform translation (using Aurelia i18n or other packages) and more.
If you do not provide any configuration value, the default is hash-based routing. This means a hash will be used in the URL. If your application requires SEO-friendly links instead of hash-based routing links, you will want to use pushState.
We are performing the configuration inside of the main.ts file, which is the default file created when using the Makes CLI tool.
By calling the customize method, you can supply a configuration object containing the property useUrlFragmentHash and supplying a boolean value. If you supply true this will enable hash mode. The default is true.
If you are working with pushState routing, you will need a base HREF value in the head of your document. The scaffolded application from the CLI includes this in the index.html file, but if you're starting from scratch or building within an existing application, you need to be aware of this.
PushState requires server-side support. This configuration is different depending on your server setup. For example, if you are using Webpack DevServer, you'll want to set the devServer historyApiFallback option to true. If you are using ASP.NET Core, you'll want to call routes.MapSpaFallbackRoute in your startup code. See your preferred server technology's documentation for more information on how to allow 404s to be handled on the client with push state.
The useHref configuration setting is something all developers working with routing in Aurelia need to be aware of. By default, the router will allow you to use both href as well as load for specifying routes.
Where this can get you into trouble are external links, mailto links and other types of links that do not route. A simple example looks like this:
By default, this seemingly innocent and common scenario will trigger the router and cause an error in the console.
You have two options when it comes to working with external links. You can specify the link as external using the external attribute.
Or, you can set useHref to false and only ever use the load attribute for routes.
If you are using the router to render components in your application, there might be situations where a component attempts to be rendered that do not exist. This can happen while using direct routing (not configured routing)
This section is not for catch-all/404 routes. If you are using configured routing, you are looking for the .
To add in fallback behavior, we can do this in two ways. The fallback attribute on the <au-viewport> element or in the router customize method (code).
Let's create the missing-page component (this is required, or the fallback behavior will not work). First, we'll create the view model for our missing-page component.
For the fallback component, an ID gets passed as a parameter which is the value from the URL. If you were to attempt to visit a non-existent route called "ROB," the missingComponent value would be ROB.
Now, the HTML.
By using the fallback property on the customize method when we register the router, we can pass a component.
Sometimes the fallback attribute can be the preferred approach to registering a fallback. Import your fallback component and pass the name to the fallback attribute. The same result, but it doesn't require touching the router registration.
The swapStrategy configuration value determines how contents are swapped in a viewport when transitioning. Sometimes, you might want to change this depending on the type of data you are working with or how your routes are loaded. A good example of configuring the swap order is when you're working with animations.
attach-next-detach-current (default)
attach-detach-simultaneously
detach-current-attach-next
detach-attach-simultaneously
Still, confused or need an example? You can find an example application with routing over on GitHub .
import Aurelia from 'aurelia';
// Our router configuration import to register the Router with Aurelia's DI
import { RouterConfiguration } from '@aurelia/router';
import { MyApp } from './my-app';
Aurelia
.register(RouterConfiguration)
.app(MyApp)
.start();import { HomePage } from './home-page';
export class MyApp {
static routes = [
{
path: '',
component: HomePage,
title: 'Home'
},
];
}<h1>Homepage</h1>
<p>This is the homepage.</p>export class HomePage {
}<!-- Two routes using the load attribute containing the path of the route -->
<a load="/">Home</a>
<!-- This is where our routed components are loaded -->
<au-viewport></au-viewport>import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
Aurelia
.register(
RouterConfiguration.customize({
title: '${componentTitles}${appTitleSeparator}My App'
}))
.app(component)
.start();import { RouterConfiguration, RoutingInstruction, Navigation } from '@aurelia/router';
import { Aurelia } from 'aurelia';
import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
import { MyApp } from './my-app';
Aurelia
.register(RouterConfiguration.customize({
title: {
transformTitle: (title: string, instruction: RoutingInstruction, navigation: Navigation) => {
return `${title} - MYAPP`;
}
}
})
.app(MyApp)
.start();import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
Aurelia
.register(RouterConfiguration.customize({ useUrlFragmentHash: false }))
.app(component)
.start();<head>
<base href="/">
</head><a href="mailto:[email protected]">Email Me</a><a href="mailto:[email protected]" external>Email Me</a>import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
Aurelia
.register(RouterConfiguration.customize({
useHref: false
}))
.app(component)
.start();export class MissingPage {
public static parameters = ['id'];
public missingComponent: string;
public loading(parameters: {id: string}): void {
this.missingComponent = parameters.id;
}
}<h3>Ouch! I couldn't find '${missingComponent}'!</h3>import Aurelia from 'aurelia';
import { RouterConfiguration } from '@aurelia/router';
import { MyApp } from './my-app';
import { MissingPage } from './missing-page';
Aurelia
.register(RouterConfiguration.customize({
fallback: MissingPage,
}))
.app(MyApp)
.start();<import from="./missing-page"></import>
<au-viewport fallback="missing-page"></au-viewport>Watching data for changes, including support for expressions where you want to watch for changes to one or more dependencies and react accordingly.
Unlike other observation strategies detailed in the observation section, the @watch functionality allows you to watch for changes in your view models. If you worked with the computedFrom decorator in Aurelia 1, the watch decorator is what you would replace it with.
Aurelia provides a way to author your components in a reactive programming model with the @watch decorator. Decorating a class or a method inside it with the @watch decorator, the corresponding method will be called whenever the watched value changes.
import { watch } from '@aurelia/runtime-html';
// on class
@watch(expressionOrPropertyAccessFn, changeHandlerOrCallback)
class MyClass {}
// on method
class MyClass {
@watch(expressionOrPropertyAccessFn)
someMethod() {}
}expressionOrPropertyAccessFn
string | IPropertyAccessFn
Watch expression specifier
changeHandlerOrCallback
string | IWatcherCallback
The callback that will be invoked when the value evaluated from watch expression has changed. If a name is given, it will be used to resolve the callback ONCE. This callback will be called with 3 parameters: (1st) new value from the watched expression. (2nd) old value from the watched expression (3rd) the watched instance. And the context of the function call will be the instance, same with the 3rd parameter.
The @watch decorator allows you to react to changes on a property or computed function.
In the following example, we will call a function every time the name property in our view model is changed.
import { watch } from '@aurelia/runtime-html';
class NameComponent {
name = '';
@watch('name')
nameChange(newName, oldName) {
console.log(newName); // The new name value
console.log(oldName); // The old name value
}
}This is referred to in Aurelia as an expression. You can also observe properties on things like arrays for changes which might be familiar to you if you worked with Aurelia 1 and the @computedFrom decorator.
This is what an expression looks like observing an array length for changes:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch('packages.length')
log(newCount, oldCount) {
if (newCount > oldCount) {
// new packages came
} else {
// packages delivered
}
}
}Sometimes you want to watch multiple values in a component, so you need to create an expression. A computed function is a function provided to the @watch decorator, which allows you to do comparisons on multiple values.
To illustrate how you can do this, here is an example:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch(post => post.packages.length)
log(newCount, oldCount) {
if (newCount > oldCount) {
// new packages came
} else {
// packages delivered
}
}
}In this example, the log method of PostOffice will be called whenever a new package is added to, or an existing package is removed from the packages array. The first argument of our callback function is the view model, allowing us to access class properties and methods.
import { watch } from '@aurelia/runtime-html';
@watch('counter', (newValue, oldValue, app) => app.log(newValue))
class App {
counter = 0;
log(whatToLog) {
console.log(whatToLog);
}
}The method name will be used to resolve the function once, which means changing the method after the instance has been created will not be recognized.
import { watch } from '@aurelia/runtime-html';
@watch('counter', 'log')
class App {
counter = 0;
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
@watch('counter', function(newValue, oldValue, app) {
app.log(newValue);
// or use this, it will point to the instance of this class
this.log(newValue);
})
class App {
counter = 0;
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
@watch(function (app) { return app.counter }, (newValue, oldValue, app) => app.log(newValue))
class App {
counter = 0;
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
@watch(app => app.counter, (newValue, oldValue, app) => app.log(newValue))
class App {
counter = 0;
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
class App {
counter = 0;
@watch('counter')
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
class App {
counter = 0;
@watch(function(app) { return app.counter })
log(whatToLog) {
console.log(whatToLog);
}
}import { watch } from '@aurelia/runtime-html';
class App {
counter = 0;
@watch(app => app.counter)
log(whatToLog) {
console.log(whatToLog);
}
}During
bindinglifecycle, bindings created by@watchdecorator haven't been activated yet, which means mutations won't be reacted to:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch(post => post.packages.length)
log(newCount, oldCount) {
console.log(`packages changes: ${oldCount} -> ${newCount}`);
}
// lifecycle
binding() {
this.packages.push({ id: 1, name: 'xmas toy', delivered: false });
}
}There will be no log in the console.
During
boundlifecycle, bindings created by@watchdecorator have been activated, and mutations will be reacted to:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch(post => post.packages.length)
log(newCount, oldCount) {
console.log(`packages changes: ${oldCount} -> ${newCount}`);
}
// lifecycle
bound() {
this.packages.push({ id: 1, name: 'xmas toy', delivered: false });
}
}There will be 1 log in the console that looks like this: packages changes: 0 -> 1.
During
detachinglifecycle, bindings created by@watchdecorator have not been de-activated yet, and mutations will still be reacted to:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch(post => post.packages.length)
log(newCount, oldCount) {
console.log(`packages changes: ${oldCount} -> ${newCount}`);
}
// lifecycle
detaching() {
this.packages.push({ id: 1, name: 'xmas toy', delivered: false });
}
}There will be 1 log in the console that looks like this: packages changes: 0 -> 1.
During
unbindinglifecycle, bindings created by@watchdecorator have been deactivated, and mutations won't be reacted to:
import { watch } from '@aurelia/runtime-html';
class PostOffice {
packages = [];
@watch(post => post.packages.length)
log(newCount, oldCount) {
console.log(`packages changes: ${oldCount} -> ${newCount}`);
}
// lifecycle
unbinding() {
this.packages.push({ id: 1, name: 'xmas toy', delivered: false });
}
}There will be no log in the console.
By default, a watcher will be created for a @watch() decorator. This watcher will start observing before bound lifecycle of components. How the observation works will depend on the first parameter given.
If a string or a symbol is given, it will be used as an expression to observe, similar to how an expression in Aurelia templating works.
If a function is given, it will be used as a computed getter to observe dependencies and evaluate the value to pass into the specified method. Two mechanisms can be employed:
For JavaScript environments with native proxy support: Proxy will be used to trap & observe property read. It will also observe collections (such as an array, map and set) based on invoked methods. For example, calling .map(item => item.value) on an array should observe the mutation of that array and the property value of each item inside the array.
For environments without native proxy support: the 2nd parameter inside the computed getter can be used to observe (or register) dependencies manually. This is the corresponding watcher created from a @watch decorator. It has the following interface:
interface IWatcher {
observeProperty(obj: object, key: string | number | symbol): void;
observeCollection(collection: Array | Map | Set): void;
}An example is:
import { watch } from '@aurelia/runtime-html';
class Contact {
firstName = 'Chorris';
lastName = 'Nuck';
@watch((contact, watcher) => {
watcher.observeProperty(contact, 'firstName');
watcher.observeProperty(contact, 'lastName');
return `${contact.firstName} ${contact.lastName}`;
})
validateFullName(fullName) {
if (fullName === 'Chuck Norris') {
this.faint();
}
}
}The firstName and lastName properties of contact components are being observed manually. And every time either firstName, or lastName change, the computed getter is run again, and the dependencies will be observed again. Observers are cached, and the same observer won't be added more than once, old observers from the old computed getter run will also be disposed of, so you won't have to worry about stale dependencies or memory leaks.
Automatic array observation
By default, in the computed getter, array mutation method such as .push(), .pop(), .shift(), .unshift(), .splice(), and .reverse() are not observed, as there are no clear indicators of the dependencies to collect from those methods.
It is best to avoid mutation on dependencies collected inside a computed getter.
// don't do this
@watch(object => object.counter++)
someMethod() {}
// don't do these
@watch(object => object.someArray.push(...args))
@watch(object => object.someArray.pop())
@watch(object => object.someArray.shift())
@watch(object => object.someArray.unshift())
@watch(object => object.someArray.splice(...args))
@watch(object => object.someArray.reverse())
someMethod() {}To ensure identity equality with proxies, always be careful with objects not accessed from the first parameter passed into the computed getter. Better get the raw underlying object before doing the strict comparison with ===.
import { watch } from '@aurelia/runtime-html';
const defaultOptions = {};
class MyClass {
options = defaultOptions;
@watch(myClass => myClass.options === defaultOptions ? null : myClass.options)
applyCustomOptions() {
// ...
}
}In this example, even if options on a MyClass instance has never been changed, the comparison of myClass.options === defaultOptions will still return false, as the actual value for myClass.options is a proxied object wrapping the real object, and thus is always different with defaultOptions.
Dependency tracking inside a watch computed getter is done synchronously, which means returning a promise or having an async function won't work properly.
Don't do the following:
import { watch } from '@aurelia/runtime-html';
class MyClass {
// don't do this
@watch(async myClassInstance => myClassinstance.options)
applyCustomOptions() {}
// don't do this
@watch(myClassInstance => {
Promise.resolve().then(() => {
return myClassinstance.options
})
})
}import {
IRouteViewModel,
Params,
RouteNode,
NavigationInstruction,
} from '@aurelia/router-lite';
export class MyComponent implements IRouteViewModel {
canLoad?(
params: Params,
next: RouteNode,
current: RouteNode | null
): boolean
| NavigationInstruction
| NavigationInstruction[]
| Promise<boolean | NavigationInstruction | NavigationInstruction[]>;
loading?(
params: Params,
next: RouteNode,
current: RouteNode | null
): void | Promise<void>;
canUnload?(
next: RouteNode | null,
current: RouteNode
): boolean | Promise<boolean>;
unloading?(
next: RouteNode | null,
current: RouteNode
): void | Promise<void>;
}import { lifecycleHooks } from 'aurelia';
import {
IRouteViewModel,
Params,
RouteNode,
NavigationInstruction
} from '@aurelia/router-lite';
@lifecycleHooks()
class MySharedHooks {
canLoad?(
viewModel: IRouteViewModel,
params: Params,
next: RouteNode,
current: RouteNode | null
): boolean
| NavigationInstruction
| NavigationInstruction[]
| Promise<boolean | NavigationInstruction | NavigationInstruction[]>;
loading?(
viewModel: IRouteViewModel,
params: Params,
next: RouteNode,
current: RouteNode | null
): void | Promise<void>;
canUnload?(
viewModel: IRouteViewModel,
next: RouteNode | null,
current: RouteNode
): boolean | Promise<boolean>;
unloading?(
viewModel: IRouteViewModel,
next: RouteNode | null,
current: RouteNode
): void | Promise<void>;
}import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
import { Login } from './login';
import { Forbidden } from './forbidden';
import { Restricted } from './restricted';
@route({
routes: [
{ path: '', redirectTo: 'home' },
{
path: 'home',
component: Home,
},
{
path: 'login',
component: Login,
},
{
path: 'forbidden',
component: Forbidden,
},
{
path: 'about',
component: About,
data: {
claim: { type: 'read', resource: 'foo' },
},
},
{
path: 'restricted',
component: Restricted,
data: {
claim: { type: 'manage', resource: 'foo' },
},
},
],
})
export class MyApp {}import {
IRouteViewModel,
NavigationInstruction,
Params,
RouteNode,
} from '@aurelia/router-lite';
import { lifecycleHooks } from '@aurelia/runtime-html';
import { IAuthenticationService } from './authentication-service';
@lifecycleHooks()
export class AuthenticationHook {
public constructor(
@IAuthenticationService private readonly authService: IAuthenticationService
) {}
public canLoad(
_viewmodel: IRouteViewModel,
_params: Params,
next: RouteNode
): boolean | NavigationInstruction {
if (!next.data?.claim || this.authService.currentClaims != null)
return true;
// we add the current url to the return_url query to the login page,
// so that login page can redirect to that url after successful login.
return `login?return_url=${next.computeAbsolutePath()}`;
}
}import {
IRouteViewModel,
NavigationInstruction,
Params,
RouteNode,
} from '@aurelia/router-lite';
import { lifecycleHooks } from '@aurelia/runtime-html';
import { Claim } from './authentication-service';
import { IAuthenticationService } from './authentication-service';
@lifecycleHooks()
export class AuthorizationHook {
public constructor(
@IAuthenticationService private readonly authService: IAuthenticationService
) {}
public canLoad(
_viewmodel: IRouteViewModel,
_params: Params,
next: RouteNode
): boolean | NavigationInstruction {
const claim = next.data?.claim as Claim;
if (!claim) return true;
if (this.authService.hasClaim(claim.type, claim.resource)) return true;
return 'forbidden';
}
}import { RouterConfiguration } from '@aurelia/router-lite';
import { Aurelia, StandardConfiguration } from '@aurelia/runtime-html';
import { AuthenticationHook } from './authentication-hook';
import { IAuthenticationService } from './authentication-service';
import { AuthorizationHook } from './authorization-hook';
import { MyApp as component } from './my-app';
(async function () {
const host = document.querySelector<HTMLElement>('app');
const au = new Aurelia();
au.register(
StandardConfiguration,
RouterConfiguration,
IAuthenticationService,
// register the first lifecycle hook
AuthenticationHook,
// register the second lifecycle hook
AuthorizationHook
);
au.app({ host, component });
await au.start();
})().catch(console.error);import { ILogger } from '@aurelia/kernel';
import { IRouteViewModel, Params, RouteNode } from '@aurelia/router-lite';
import { lifecycleHooks } from '@aurelia/runtime-html';
@lifecycleHooks()
export class Hook1 {
public static readonly scope = 'hook1';
private readonly logger: ILogger;
public constructor(@ILogger logger: ILogger) {
this.logger = logger.scopeTo(Hook1.scope);
}
public canLoad(_vm: IRouteViewModel, _params: Params, next: RouteNode): boolean {
this.logger.debug(`canLoad '${next.computeAbsolutePath()}'`);
return true;
}
public loading(_vm: IRouteViewModel, _params: Params, next: RouteNode) {
this.logger.debug(`loading '${next.computeAbsolutePath()}'`);
}
public canUnload(_vm: IRouteViewModel, _next: RouteNode, current: RouteNode): boolean {
this.logger.debug(`canUnload '${current.computeAbsolutePath()}'`);
return true;
}
public unloading(_vm: IRouteViewModel, _next: RouteNode, current: RouteNode) {
this.logger.debug(`unloading '${current.computeAbsolutePath()}'`);
}
}
@lifecycleHooks()
export class Hook2 {
public static readonly scope = 'hook2';
private readonly logger: ILogger;
public constructor(@ILogger logger: ILogger) {
this.logger = logger.scopeTo(Hook2.scope);
}
public canLoad(_vm: IRouteViewModel, _params: Params, next: RouteNode): boolean {
this.logger.debug(`canLoad '${next.computeAbsolutePath()}'`);
return true;
}
public loading(_vm: IRouteViewModel, _params: Params, next: RouteNode) {
this.logger.debug(`loading '${next.computeAbsolutePath()}'`);
}
public canUnload(_vm: IRouteViewModel, _next: RouteNode, current: RouteNode): boolean {
this.logger.debug(`canUnload '${current.computeAbsolutePath()}'`);
return true;
}
public unloading(_vm: IRouteViewModel, _next: RouteNode, current: RouteNode) {
this.logger.debug(`unloading '${current.computeAbsolutePath()}'`);
}
}2023-01-29T20:03:23.885Z [DBG hook1] canLoad ''
2023-01-29T20:03:23.887Z [DBG hook2] canLoad ''
2023-01-29T20:03:23.888Z [DBG hook1] loading ''
2023-01-29T20:03:23.888Z [DBG hook2] loading ''
2023-01-29T20:10:09.403Z [DBG hook1] canUnload ''
2023-01-29T20:10:09.407Z [DBG hook2] canUnload ''
2023-01-29T20:10:09.410Z [DBG hook1] canLoad 'c1/42'
2023-01-29T20:10:09.410Z [DBG hook2] canLoad 'c1/42'
2023-01-29T20:10:09.410Z [DBG hook1] unloading ''
2023-01-29T20:10:09.411Z [DBG hook2] unloading ''
2023-01-29T20:10:09.411Z [DBG hook1] loading 'c1/42'
2023-01-29T20:10:09.411Z [DBG hook2] loading 'c1/42'// child1.ts
import { customElement } from '@aurelia/runtime-html';
import { Hook1, Hook3 } from './hooks';
@customElement({
dependencies: [Hook1, Hook3],
})
export class ChildOne {}
// child2.ts
import { customElement } from '@aurelia/runtime-html';
import { Hook2 } from './hooks';
@customElement({
dependencies: [Hook2],
})
export class ChildTwo {}2023-02-01T21:59:23.525Z [DBG hook2] canLoad 'c2/43'
2023-02-01T21:59:23.527Z [DBG hook2] loading 'c2/43'
2023-02-01T21:59:25.353Z [DBG hook2] canUnload 'c2/43'
2023-02-01T21:59:25.355Z [DBG hook1] canLoad 'c1/42'
2023-02-01T21:59:25.355Z [DBG hook3] canLoad 'c1/42'
2023-02-01T21:59:25.356Z [DBG hook2] unloading 'c2/43'
2023-02-01T21:59:25.356Z [DBG hook1] loading 'c1/42'
2023-02-01T21:59:25.357Z [DBG hook3] loading 'c1/42'2023-02-02T19:12:51.503Z [DBG hook1] canLoad 'c1/42'
2023-02-02T19:12:51.505Z [DBG hook2] canLoad 'c1/42'
2023-02-02T19:12:51.506Z [DBG hook1] loading 'c1/42'
2023-02-02T19:12:51.506Z [DBG hook2] loading 'c1/42'
2023-02-02T19:12:55.287Z [DBG hook1] canUnload 'c1/42'
2023-02-02T19:12:55.288Z [DBG hook2] canUnload 'c1/42'
2023-02-02T19:12:55.288Z [DBG hook1] canLoad 'c1/43'App tasks provide injection points to run code at certain points in the compiler lifecycle, allowing you to interface with different parts of the framework and execute code.
Falling between component lifecycles and lifecycle hooks, app tasks offer injection points into Aurelia applications that occur at certain points of the compiler lifecycle. Think of them as higher-level framework hooks.
The app task API has the following calls:
creating — Runs just before DI creates the root component - last chance to register deps that must be injected into the root
hydrating — Runs after instantiating the root view, but before compiling itself and instantiating the child elements inside it - good chance for a router to do some initial work
hydrated — Runs after self-hydration of the root controller, but before hydrating the child element inside - good chance for a router to do some initial work
activating — Runs right before the root component is activated - in this phase, scope hierarchy is formed, and bindings are getting bound
activated — Runs right after the root component is activated - the app is now running
deactivating — Runs right before the root component is deactivated - in this phase, scope hierarchy is unlinked, and bindings are getting unbound
deactivated — Runs right after the root component is deactivated
You register the app tasks with the container during the instantiation of Aurelia or within a plugin (which Aurelia instantiates). In fact, there are many examples of using app tasks throughout the documentation. Such as , , and the section on using the .
Many of Aurelia's own plugins use app tasks to perform operations involving registering numerous components and asynchronous parts of the framework.
A good example of where app tasks can come in handy is plugins that need to register things with the DI container. The app task methods can accept a callback but also a key and callback, which can be asynchronous.
In the above example, we await importing a file which could be a JSON file or something else inside the task itself. Then, we register it with DI.
Another great example of using app tasks is the dialog plugin that comes with Aurelia. The deactivating task closes all models using the dialogue service, as you can see .
In Aurelia applications, app tasks are registered through the register method and will be handled inside of your main.ts file.
Within a plugin, the code is similar. You would be exporting a function which accepts the DI container as its first argument, allowing you to register tasks and other resources.
Using code taken from a real Aurelia 2 application, we will show you how you might use App Tasks in your Aurelia applications. One such example is Google Analytics.
We then pass the GoogleAnalyticsTask constant and register it with the container inside main.ts
The above code runs during the activating app task and registers/attaches the Google Analytics SDK to our application.
This example shows how to use an App Task for dynamically loading features based on user roles. It's particularly useful in applications with role-based access control.
In this example, during the activating phase, the application checks the user's roles and dynamically imports features based on these roles.
Setting up a global error handler during the creating task ensures that any uncaught errors in the application are handled in a unified manner.
This example uses the creating task to set up a global error handler that intercepts and processes uncaught errors.
This example demonstrates setting up application telemetry using an App Task, which is useful for gathering usage metrics.
Here, the hydrated task initializes and starts a telemetry session after the application is hydrated.
import { IContainer } from '@aurelia/kernel';
import { AppTask, DI, Registration } from 'aurelia';
Aurelia.register(
AppTask.hydrating(IContainer, async container => {
if (config.enableSpecificOption) {
const file = await import('file');
cfg.register(Registration.instance(ISpecificOption, file.do());
}
Registration.instance(IBootstrapV5Options, config).register(container);
})
);import Aurelia, { AppTask } from 'aurelia';
const au = new Aurelia();
au.register(
AppTask.activating(() => {
console.log('actiating or before activate');
})
);export function register(container: IContainer) {
container.register(
AppTask.activating(() => {
console.log('activating or before activate');
})
)
}import { IGoogleAnalytics } from './../resources/services/google-analytics';
import { AppTask } from 'aurelia';
export const GoogleAnalyticsTask = AppTask.activating(IGoogleAnalytics, (ga) => {
ga.init('UA-44935027-5');
ga.attach();
});Aurelia.register(GoogleAnalyticsTask);import { IUserService, UserRoles } from './../services/user-service';
import { AppTask } from 'aurelia';
export const DynamicFeatureLoadingTask = AppTask.activating(IUserService, async (userService) => {
const userRoles = await userService.getCurrentUserRoles();
if (userRoles.includes(UserRoles.Admin)) {
await import('./features/admin-feature');
}
if (userRoles.includes(UserRoles.User)) {
await import('./features/user-feature');
}
});
// Then, register this task in main.ts
Aurelia.register(DynamicFeatureLoadingTask);import { AppTask, ILogger } from 'aurelia';
import { GlobalErrorHandler } from './../services/global-error-handler';
export const GlobalErrorHandlingTask = AppTask.creating(ILogger, logger => {
window.onerror = (message, source, lineno, colno, error) => {
const errorHandler = new GlobalErrorHandler(logger);
errorHandler.handle(error);
return true; // Prevents the default browser error handling
};
});
// Register this task in main.ts
Aurelia.register(GlobalErrorHandlingTask);import { AppTask } from 'aurelia';
import { TelemetryService } from './../services/telemetry-service';
export const TelemetrySetupTask = AppTask.hydrated(TelemetryService, telemetryService => {
telemetryService.initialize();
telemetryService.startSession();
});
// Register this task in main.ts
Aurelia.register(TelemetrySetupTask);Binding behaviors are a category of view resources, just like value converters, custom attributes and custom elements. Binding behaviors are most like value converters in that you use them declaratively in binding expressions to affect the binding.
The primary difference between a binding behavior and a value converter is binding behaviors have full access to the binding instance, throughout its lifecycle. Contrast this with a value converter, which can only intercept values passing from the model to the view and visa versa.
The additional "access" afforded to binding behaviors gives them the ability to change the behaviour of the binding, enabling a lot of interesting scenarios, which you'll see below.
Aurelia ships with a handful of behaviors out of the box to enable common scenarios. The first is the throttle binding behavior which limits the rate at which the view-model is updated in two-way bindings or the rate at which the view is updated in to-view binding scenarios.
By default, throttle will only allow updates every 200ms. You can customize the rate, of course. Here are a few examples.
Updating a property, at most, every 200ms
HTML
<input type="text" value.bind="query & throttle">The first thing you probably noticed in the example above is the & symbol, used to declare binding behavior expressions. Binding behavior expressions use the same syntax pattern as value converter expressions:
Binding behaviors can accept arguments: firstName & myBehavior:arg1:arg2:arg3
A binding expression can contain multiple binding behaviors: firstName & behavior1 & behavior2:arg1.
Binding expressions can also include a combination of value converters and binding behaviors: ${foo | upperCase | truncate:3 & throttle & anotherBehavior:arg1:arg2}.
Here's another example using throttle, demonstrating the ability to pass arguments to the binding behavior:
Updating a property, at most, every 850ms
<input type="text" value.bind="query & throttle:850">The throttle behavior is particularly useful when binding events to methods on your view-model. Here's an example with the mousemove event:
Handling an event, at most, every 200ms
<div mousemove.delegate="mouseMove($event) & throttle"></div>Sometimes, it's desirable to forcefully run the throttled update so that the application syncs the latest values. This can happen in a form when a user previously was typing into a throttled form field and hit the tab key to go to the next field, as an example. The throttle binding behavior supports this scenario via signal. These signals can be added via the 2nd parameter, like the following example:
<input value.bind="value & throttle :200 :`finishTyping`" blur.trigger="signaler.dispatchSignal('finishTyping')">
<!-- or it can be a list of signals -->
<input value.bind="value & throttle :200 :[`finishTyping`, `newUpdate`]">The debounce binding behavior is another rate-limiting binding behavior. Debounce prevents the binding from being updated until a specified interval has passed without any changes.
A common use case is a search input that triggers searching automatically. You wouldn't want to make a search API on every change (every keystroke). It's more efficient to wait until the user has paused typing to invoke the search logic.
Update after typing stopped for 200ms
<input type="text" value.bind="query & debounce">Update after typing stopped for 850ms
<input type="text" value.bind="query & debounce:850">Like throttle, the debounce binding behavior shines in event binding.
Here's another example with the mousemove event:
Call mouseMove after the mouse stops moving for 500ms
<div mousemove.delegate="mouseMove($event) & debounce:500"></div>Sometimes, it's desirable to forcefully run the throttled update so that the application syncs the latest values. This can happen in a form when a user previously was typing into a throttled form field and hit the tab key to go to the next field, as an example. Similar to the throttle binding behavior, The debounce binding behavior supports this scenario via signal. These signals can be added via the 2nd parameter, like the following example:
<input value.bind="value & debounce :200 :`finishTyping`" blur.trigger="signaler.dispatchSignal('finishTyping')">
<!-- or it can be a list of signals -->
<input value.bind="value & debounce :200 :[`finishTyping`, `newUpdate`]">The update trigger allows you to override the input events that cause the element's value to be written to the view model. The default events are change and input.
Here's how you would tell the binding to only update the model on blur:
Update on blur
<input value.bind="firstName & updateTrigger:'blur'> Multiple events are supported:
Update with multiple events
<input value.bind="firstName & updateTrigger:'blur':'paste'>The signal binding behavior enables you to "signal" the binding to refresh. This is especially useful when a binding result is impacted by global changes outside **** the observation path.
For example, if you have a "translate" value converter that converts a key to a localized string- e.g. ${'greeting-key' | translate} and your site allows users to change the current language, how would you refresh the bindings when that happens?
Another example is a value converter that uses the current time to convert a record's datetime to a "time ago" value: posted ${postDateTime | timeAgo}. When this binding expression is evaluated, it will correctly result in posted a minute ago. As time passes, it will eventually become inaccurate. How can we refresh this binding periodically to correctly display 5 minutes ago, then 15 minutes ago, an hour ago, etc?
Here's how you would accomplish this using the signal binding behaviour:
Using a Signal
posted ${postDateTime | timeAgo & signal:'my-signal'}In the binding expression above, we're using the signal binding behavior to assign the binding a "signal name" of my-signal. Signal names are arbitrary. You can give multiple bindings the same signal name if you want to signal multiple bindings simultaneously.
Here's how we can use the ISignaler to signal the bindings periodically:
Signaling Bindings
import { ISignaler } from 'aurelia';
export class MyApp {
constructor(@ISignaler readonly signaler: ISignaler) {
setInterval(() => signaler.signal('my-signal'), 5000);
}
}With the oneTime binding behavior you can specify that string interpolated bindings should happen once. Simply write:
One-time String Interpolation
<span>${foo & oneTime}</span>This is an important feature to expose. One-time bindings are the most efficient type of binding because they don't incur any property observation overhead.
There are also binding behaviors for toView and twoWay which you could use like this:
To-view and two-way binding behaviours
<input value.bind="foo & toView">
<input value.to-view="foo">
<input value.bind="foo & twoWay">
<input value.two-way="foo"> The casing for binding modes differs depending on whether they appear as a binding command or as a binding behavior. Because HTML is case-insensitive, binding commands cannot use capitals. Thus, when specified in this place, the binding modes use lowercase, dashed names. However, when used within a binding expression as a binding behavior, they must not use a dash because that is not a valid symbol for variable names in JavaScript. So, in this case, camel casing is used.
With the self binding behavior, you can specify that the event handler will only respond to the target to which the listener was attached, not its descendants.
For example, in the following markup
Self-binding behavior
<panel>
<header mousedown.delegate='onMouseDown($event)' ref='header'>
<button>Settings</button>
<button>Close</button>
</header>
</panel>onMouseDown is your event handler, and it will be called not only when user mousedown on header element, but also all elements inside it, which in this case are the buttons settings and close. However, this is not always the desired behaviour. Sometimes, you want the component only to react when the user clicks on the header itself, not the buttons. To achieve this, onMouseDown method needs some modification:
Handler without self-binding behavior
// inside component's view model class
onMouseDown(event) {
// if mousedown on the header's descendants. Do nothing
if (event.target !== header) return;
// mousedown on header, start listening for mousemove to drag the panel
// ...
}This works, but business/ component logic is now mixed up with DOM event handling, which is unnecessary. Using self binding behaviour can help you achieve the same goal without filling up your methods with unnecessary code:
Using self-binding behavior
<panel>
<header mousedown.delegate='onMouseDown($event) & self'>
<button class='settings'></button>
<button class='close'></button>
</header>
</panel>Using self-binding behavior
// inside component's view model class
onMouseDown(event) {
// No need to perform check, as the binding behavior will ensure check
// if (event.target !== header) return;
// mousedown on header, start listening for mousemove to drag the panel
// ...
}You can build custom binding behaviors just like you can build value converters. Instead of toView and fromView methods, you'll create bind(binding, scope, [...args]) and unbind(binding, scope) methods. In the bind method, you'll add your behavior to the binding, and in the unbind method, you should clean up whatever you did in the bind method to restore the binding instance to its original state.
The binding argument is the binding instance whose behavior you want to change. It's an implementation of the Binding interface. The scope argument is the binding's data context. It provides access to the model the binding will be bound to via its bindingContext and overrideContext properties.
Here's a custom binding behavior that calls a method on your view model each time the binding's updateSource / updateTarget and callSource methods are invoked.
const interceptMethods = ['updateTarget', 'updateSource', 'callSource'];
export class InterceptBindingBehavior {
bind(scope, binding) {
let i = interceptMethods.length;
while (i--) {
let methodName = interceptMethods[i];
let method = binding[method];
if (!method) {
continue;
}
binding[`intercepted-${methodName}`] = method;
binding[methodName] = method.bind(binding);
}
}
unbind(scope, binding) {
let i = interceptMethods.length;
while (i--) {
let methodName = interceptMethods[i];
if (!binding[methodName]) {
continue;
}
binding[methodName] = binding[`intercepted-${methodName}`];
binding[`intercepted-${methodName}`] = null;
}
}
}
<import from="./intercept-binding-behavior"></import>
<div mousemove.delegate="mouseMove($event) & intercept:myFunc"></div>
<input value.bind="foo & intercept:myFunc">Logs the current binding context to the console whenever the binding updates. This is useful for understanding the data context of a particular binding at runtime.
import { bindingBehavior } from '@aurelia/runtime-HTML';
import { type IBinding, type Scope } from '@aurelia/runtime';
export class LogBindingContextBehavior {
public bind(scope: Scope, binding: IBinding) {
const originalUpdateTarget = binding.updateTarget;
binding.updateTarget = (value) => {
console.log('Binding context:', scope.bindingContext);
originalUpdateTarget(value);
};
}
}
bindingBehavior('logBindingContext')(LogBindingContextBehavior);<import from="./log-binding-behavior"></import>
<input value.bind="name & logBindingContext"></div>Temporarily adds a tooltip to the element, showing the current value of the binding. This can be a quick way to inspect binding values without console logging.
import { bindingBehavior } from '@aurelia/runtime-HTML';
import { type IBinding, type Scope } from '@aurelia/runtime';
export class InspectBindingBehavior {
public bind(scope: Scope, binding: IBinding) {
const originalUpdateTarget = binding.updateTarget;
binding.updateTarget = (value) => {
originalUpdateTarget(value);
binding.target.title = `Current value: ${value}`;
};
}
}
bindingBehavior('inspect')(InspectBindingBehavior);<import from="./inspect-binding-behavior"></import>
<input value.bind="name & inspect"></div>This binding behavior will highlight an element by changing its background color temporarily whenever the binding's target value changes. This visual cue can help developers quickly identify which UI parts react to data changes.
import { bindingBehavior } from '@aurelia/runtime-html';
import { type IBinding, type Scope } from '@aurelia/runtime';
export class HighlightUpdatesBindingBehavior {
public bind(scope: Scope, binding: IBinding, highlightColor: string = 'yellow', duration: number = 500) {
const originalUpdateTarget = binding.updateTarget;
binding.updateTarget = (value) => {
originalUpdateTarget.call(binding, value);
const originalBg = binding.target.style.backgroundColor;
binding.target.style.backgroundColor = highlightColor;
setTimeout(() => {
binding.target.style.backgroundColor = originalBg;
}, duration);
};
}
}
bindingBehavior('highlightUpdates')(HighlightUpdatesBindingBehavior);<import from="./highlight-updates-binding-behavior"></import>
<div textContent.bind="user.message & highlightUpdates:'lightblue':'1000'"></div>Understand the scope and binding context.
You might have noticed the words "Scope", "binding context", and "override context" in other places in the documentation or while working with Aurelia in general. Although you can go a long way without even understanding what these are (Aurelia is cool that way), these are some (of many) powerful concepts that are essential when dealing with the lower-level Aurelia 2 API. This section explains what these terms mean.
Here's what you'll learn...
What is Scope?
What is binding context and override context?
How to troubleshoot the rare and weird data binding issues?
How is a context selected?
When we start an Aurelia app, the compilation pipeline JIT compiles the templates (HTML/markup) associated with custom elements. The compilation process demands documentation of its own and is out of this topic's scope. Without going into much detail about that, we can think of the compilation process in terms of the following steps:
Parse the template text,
Create instructions for custom elements, custom attributes, and template controllers (if, else, repeat.for etc.), and
Create a set of bindings for every instruction.
Most of the bindings also contain expressions.
<!-- interpolation binding -->
${firstName}
<!-- property binding -->
<my-el prop.bind="address.pin"></my-el>In the example above, the interpolation binding has the expression firsName, and the property binding has the expression address.pin (quite unsurprisingly, things are a bit more involved in actuality, but this abstraction will do for now).
An expression in itself might not be that interesting, but when it is evaluated, it becomes of interest. Enter scope. To evaluate an expression, we need a scope.
The expressions themselves do not hold any state or context. This means that the expression firstName only knows that given an object, it needs to grab the firstName property of that object. However, the expression, in itself, does not hold that object. The scope is the container that holds the object(s) which can be supplied to the expression when it is evaluated.
These objects are known as contexts. There are typically two types of contexts: binding context and override context. An expression can be evaluated against any of these two kinds of contexts. Even though there are a few subtle differences between these two kinds of contexts (see Override context), in terms of expression evaluation, there is no difference between these two.
One way to think about expression and binding context is in terms of functions and binding those functions with an execution context (Refer: Function.bind).
Let us consider the following example.
function foo() { return this.a ** 2; }If we invoke this function like foo(), we will get NaN. However, binding any object to it might return a more meaningful value, depending on the bound object.
function foo() { return this.a ** 2; }
const obj1 = { a: 10 };
const obj2 = { a: 20 };
console.log(foo.apply(obj1)); // 100
console.log(foo.apply(obj2)); // 400Following that analogy, the expressions are like this function, or more precisely, like the expression a ** 2 in the function. Binding contexts are like the objects used to bind the function. That is, given 2 different binding contexts, the same expression can produce different results when evaluated. Scope, as said before, wraps the binding context, almost like the scope in JavaScript. The need to have this wrapper over the binding context is explained in later sections.
Aurelia pipeline injects a $controller property to every custom element, custom attribute, and template controller. This property can be used to access the scope and binding context.
Let us consider the following example.
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: '<div>${message}</div>'
})
export class App implements ICustomElementViewModel {
public readonly message: string = 'Hello World!';
public readonly $controller: ICustomElementController<this>;
public created(): void {
const scope = this.$controller.scope;
const bindingContext = scope.bindingContext;
console.log(Object.is(bindingContext, this)); // true
console.log(bindingContext.message); // Hello World!
}
}Note that we haven't assigned any value explicitly to the $controller property, and the Aurelia pipeline assigns that. We can use the $controller.scope to access the scope and subsequently $controller.scope.bindingContext can be used to access the binding context.
Note how the bindingContext in the above example points to this, that is the current instance of App (with template controllers, this gets a little more involved; but we will leave that one out for now). However, we refer to the data source as a "context" in evaluating expressions.
The relations explored so far can be expressed as follows.
+-----------------------+
| |
| Scope |
| |
| +----------------+ |
| | | |
| | bindingContext | |
| | | |
| +----------------+ |
| |
+-----------------------+From here, let us proceed to understand what override context is.
As the name suggests, it is also a context that overrides the binding context. Aurelia gives higher precedence to the overriding context when the desired property is found there. This means that while binding if a property is found in both binding and override context, the latter will be selected to evaluate the expression.
We continue with the previous example; it renders <div>Hello World!</div>. However, things might be a bit different if we toy with the overriding context, as shown in the following example.
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: '<div>${message}</div>'
})
export class App implements ICustomElementViewModel {
public readonly message: string = 'Hello World!';
public readonly $controller: ICustomElementController<this>;
public created(): void {
const scope = this.$controller.scope;
scope.overrideContext.message = 'Hello Aurelia!';
}
}The assignment to overrideContext.message the rendered output is now <div>Hello Aurelia!</div> , instead of <div>Hello World!</div>. This is because of the existence of the property message in the overriding context.
As the assignment is made pre-binding phase (created hook in the example above), the context selection process sees that the required property exists in the overriding context and selects that with higher precedence even though a property with the same name also exists in the binding context.
Now with this information, we also have a new diagram.
+-----------------------+
| |
| Scope |
| |
| +----------------+ |
| | | |
| | bindingContext | |
| | | |
| +----------------+ |
| |
| |
| +-----------------+ |
| | | |
| | overrideContext | |
| | | |
| +-----------------+ |
| |
+-----------------------+Now let's address the question 'Why do we need override context at all?'. The reason it exists has to do with the template controllers (mostly). While writing template controllers, many times we want a context object that is not the underlying view-model instance. One such prominent example is the repeat.for template controller.
As you might know that repeat.for template controller provides contextual properties such as $index, $first, $last etc. These properties end up being in the override context.
Now imagine if those properties actually end up being in the binding context, which is often the underlying view-model instance. It would have caused a lot of other issues. First, that would have restricted you from having properties with the same name to avoid conflicts.
This, in turn, means that you need to know the template controllers you are using thoroughly to know about such restrictions, which is not a sound idea in itself. And with that, if you define a property with the same name, as used by the template controller, coupled with change observation etc., we could have found ourselves dealing with numerous bugs in the process. Override context helps us to get out of that horrific mess.
Another prominent use caseend for override context is the let binding. When not specified otherwise, the properties bound via the let binding ends up in the overriding context.
This can be seen in the example below.
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: '<let foo.bind="42"></let>${foo}'
})
export class App implements ICustomElementViewModel {
public readonly $controller: ICustomElementController<this>;
public attached(): void {
const scope = this.$controller.scope;
console.log('foo' in scope.bindingContext); // false
console.log(scope.overrideContext.foo); // 42
}
}Typically the properties for the let-bindings are view-only properties. It makes sense to have those properties in the overriding context.
The discussion so far has explained the necessity of context. However, that still does not answer the question, 'If the expressions are evaluated based on the context, why do we even need scope?'. Apart from serving as a logical container for the contexts, a scope also optionally points to the parent scope.
Let us consider the following example to understand that.
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({ name: 'foo-bar', template: `\${message} \${$parent.message}` })
export class FooBar implements ICustomElementViewModel {
public readonly message: string = 'Hello Foo-Bar!';
public readonly $controller: ICustomElementController<this>;
public binding(): void {
const scope = this.$controller.scope;
console.log(scope.parentScope.bindingContext instanceof App); // true
}
}
@customElement({
name: 'app',
template: '<foo-bar></foo-bar>',
dependencies: [FooBar]
})
export class App implements ICustomElementViewModel {
public readonly message: string = 'Hello App!';
public readonly $controller: ICustomElementController<this>;
public binding(): void {
console.log(this.$controller.scope.parentScope); // null
}
}The example above App uses the FooBar custom element, and both have property named message, initialized with different values. As expected, the rendered output in this case is Hello Foo-Bar! Hello App!.
You might have used the $parent keyword a lot, but for completeness, it should be clarified that the parent scope can be accessed using the $parent keyword. The example above FooBar#$controller.scope.parentScope.bindingContext points to the instance of App where <foo-bar> is used. In short, every scope instance has a parentScope property that points to the parent scope when available.
With this information, our diagram changes one last time.
+----------------------------+ +----------------------------+
+-->+ | | |
| | Scope | | Scope |
| | | | |
| | +--------------+ | | +--------------+ |
| | | | | | | | |
| | | parentScope | | | | parentScope +----------+
| | | | | | | | | |
| | +--------------+ | | +--------------+ | |
| | | | | |
| | +----------------+ | | +----------------+ | |
| | | | | | | | | |
| | | bindingContext | | | | bindingContext | | |
| | | | | | | | | |
| | +----------------+ | | +----------------+ | |
| | | | | |
| | +-----------------+ | | +-----------------+ | |
| | | | | | | | | |
| | | overrideContext | | | | overrideContext | | |
| | | | | | | | | |
| | +-----------------+ | | +-----------------+ | |
| | | | | |
| +----------------------------+ +----------------------------+ |
| |
+---------------------------------------------------------------------+Note that the parentScope for the scope of the root component is null.
As we are talking about scope, it needs to be noted that the term 'host scope' is used in the context of au-slot. There is no difference between a "normal" scope and a host scope; it just acts as the special marker to instruct the scope selection process to use the scope of the host element instead of the scope of the parent element.
Moreover, this is a special kind of scope that is valid only in the context of au-slot. This is already discussed in detail in the au-slot documentation, and thus not repeated here.
Now let us discuss change observation. A comprehensive discussion on change observation is a bit out of this documentation's scope. However, for this discussion, it would suffice to say that generally, whenever Aurelia binds an expression to the view, it employs one or more observers.
This is how when the value of the underlying property changes, the change is also propagated to view or other associated components. The focus of this discussion is how some interesting scenarios occur in conjunction with binding/override context and the change observation.
Let's start with a simple example.
import {
IPlatform,
} from '@aurelia/kernel';
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: `\${message}`,
})
export class App implements ICustomElementViewModel {
public message: string = 'Hello App!';
public readonly $controller: ICustomElementController<this>;
private intervalId: ReturnType<IPlatform['setInterval']>;
public constructor(
@IPlatform private readonly platform: IPlatform,
) { }
public attached(): void {
const scope = this.$controller.scope;
let i = 1;
this.intervalId = this.platform.setInterval(() => {
scope.bindingContext.message = `Hello App! #i: ${i++}`;
}, 1000);
// this.intervalId = this.platform.setInterval(() => {
// this.message = `Hello App! #i: ${i++}`;
// }, 1000);
}
public detaching(): void {
this.platform.clearInterval(this.intervalId);
}
}The example above updates the message property of the binding context every 1 second. As Aurelia is also observing the property, the interpolated output is also updated after every 1 second. Note that as the scope.bindingContext above points to the this, updating this.message that way has the same effect.
As the next example, we change the property in both the binding context and the override context.
import {
IPlatform,
} from '@aurelia/kernel';
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: `\${message}`,
})
export class App implements ICustomElementViewModel {
public message: string = 'Hello App!';
public readonly $controller: ICustomElementController<this>;
private intervalId1: ReturnType<IPlatform['setInterval']>;
private intervalId2: ReturnType<IPlatform['setInterval']>;
public constructor(
@IPlatform private readonly platform: IPlatform,
) { }
public attached(): void {
const scope = this.$controller.scope;
let i = 1;
this.intervalId1 = this.platform.setInterval(() => {
scope.bindingContext.message = `Hello Binding Context! #i: ${i++}`;
}, 1000);
this.intervalId2 = this.platform.setInterval(() => {
scope.overrideContext.message = `Hello Override Context! #i: ${i}`;
}, 1000);
}
public detaching(): void {
const platform = this.platform.
platform.clearInterval(this.intervalId1);
platform.clearInterval(this.intervalId2);
}
}Although it has been said before that the property in override context takes precedence over binding context, the output from the example above is Hello Binding Context! #i: 1, Hello Binding Context! #i: 2, and so on. The reason for this behavior is that the scope.bindingContext.message is bound to the view instead of scope.overrideContext.message, as the latter was non-existent during the binding phase (note that the values are being changed in attached lifecycle hook).
Therefore, the change observation is also applied for the scope.bindingContext.message as opposed to that of override context. This explains why updating the scope.overrideContext.message is rather 'futile' in the example above.
However, the result would have been quite different, if the message property is introduced to override context during the binding phase (or before that, for that matter).
import {
IPlatform,
} from '@aurelia/kernel';
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: `\${message}`,
})
export class App implements ICustomElementViewModel {
public message: string = 'Hello App!';
public readonly $controller: ICustomElementController<this>;
private intervalId1: ReturnType<IPlatform['setInterval']>;
private intervalId2: ReturnType<IPlatform['setInterval']>;
public constructor(
@IPlatform private readonly platform: IPlatform,
) { }
public binding(): void {
this.$controller.scope.overrideContext.message = 'Hello Override Context!';
}
public attached(): void {
const scope = this.$controller.scope;
let i = 1;
this.intervalId1 = this.platform.setInterval(() => {
scope.bindingContext.message = `Hello Binding Context! #i: ${i++}`;
}, 1000);
this.intervalId2 = this.platform.setInterval(() => {
scope.overrideContext.message = `Hello Override Context! #i: ${i}`;
}, 1000);
}
public detaching(): void {
const platform = this.platform.
platform.clearInterval(this.intervalId1);
platform.clearInterval(this.intervalId2);
}
}Note that the example above introduces the message property in the overriding context during the binding phase. When the interpolation expression is evaluated in the view, it is that property from the overriding context that ends up being bound. This means that the message property in the overriding context is also observed.
Thus, quite expectedly, every 1-second output of the above-shown example changes as Hello Override Context! #i: 1, Hello Override Context! #i: 2, and so on.
So far, we have seen various aspects of scope, binding and override context. One thing we have not addressed so far is how the contexts are selected for expression evaluation or assignment. In this section, we will look into that aspect.
The context selection process can be summed up (simplified) as follows.
IF $parent keyword is used once or more than once, THEN
traverse up the scope, the required number of parents (that is, for $parent.$parent.foo, we will go two steps/scopes up)
RETURN override context if the desired property is found there, ELSE RETURN binding context.
ELSE
LOOP till either the desired property is found in the context or the component boundary is hit. Then perform the following.
IF the desired property is found in the overriding context, return the override context.
ELSE RETURN binding context.
The first rule involving $parent should be self-explanatory. We will focus on the second part.
Let us first see an example to demonstrate the utility of the rule #2.1..
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'foo-bar',
template: `<div repeat.for="i of 3">
<div repeat.for="j of 2">
\${message} \${$parent.i} \${j}
</div>
</div>` })
export class FooBar implements ICustomElementViewModel {
public readonly message: string = 'Hello Foo-Bar!';
}
@customElement({
name: 'app',
template: '<foo-bar></foo-bar>',
dependencies: [FooBar]
})
export class App implements ICustomElementViewModel {
public message: string = 'Hello App!';
}As expected, the example produces the following output.
Hello Foo-Bar! 0 0
Hello Foo-Bar! 0 1
Hello Foo-Bar! 1 0
Hello Foo-Bar! 1 1
Hello Foo-Bar! 2 0
Hello Foo-Bar! 2 1Note that both App and FooBar initializes their own message properties. According to our rule #2.3. binding context is selected, and the corresponding message property is bound to the view. However, it is important to note that if the FooBar#message stays uninitialized, that is the message property exists neither in binding context nor in override context (of FooBar's scope), the output would have been as follows.
0 0
0 1
1 0
1 1
2 0
2 1Although it should be quite as per expectation, the point to be noted here is that the scope traversal never reaches to App in the process. This is because of the 'component boundary' clause in rule #2.1.. In case of this example, the expression evaluation starts with the scope of the innermost repeat.for, and traversed upwards.
When traversal hits the scope of FooBar, it recognize the scope as a component boundary and stops traversing any further, irrespective of whether the property is found or not. Contextually note that if you want to cross the component boundary, you need to explicitly use $parent keyword.
The rule #2.2. is also self-explanatory, as we have seen plenty of examples of overriding context precedence so far. Thus the last bit of this story boils down to the rule #2.3.. This rule facilitates using an uninitialized property in binding context by default or as a fallback, as can be seen in the example below.
import {
customElement,
ICustomElementController,
ICustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({
name: 'app',
template: `\${message}`,
})
export class App implements ICustomElementViewModel {
public message: string;
public constructor(
@IPlatform private readonly platform: IPlatform,
) { }
public attached(): void {
const platform = this.platform;
const id = platform.setTimeout(() => {
this.message = 'Hello World!';
platform.clearTimeout(id);
}, 2000);
}
}The example shown above produces Hello World! as output after 2 seconds of the invocation of the attached hook. This happens because of the fallback to binding context by the rule #2.3..
That's it! Congratulations! You have made it till the end. Go have that tea break now! Hope you have enjoyed this documentation as much as you will enjoy that tea. Have fun with Aurelia2!
How to create components that accept one or more bindable properties. You might know these as "props" if you are coming from other frameworks and libraries.
When creating components, sometimes you will want the ability for data to be passed into them instead of their host elements. The @bindable decorator allows you to specify one or more bindable properties for a component.
The @bindable attribute also can be used with custom attributes as well as custom elements. The decorator denotes bindable properties on components on the view model of a component.
import { bindable } from 'aurelia';
export class LoaderComponent {
@bindable loading = false;
}This will allow our component to be passed in values. Our specified bindable property here is called loading and can be used like this:
<loader loading.bind="true"></loader>In the example above, we are binding the boolean literal true to the loading property.
Instead of literal, you can also bind another property (loadingVal in the following example) to the loading property.
<loader loading.bind="loadingVal"></loader>As seen in the following example, you can also bind values without the loading.bind part.
<loader loading="true"></loader>Aurelia treats attribute values as strings. This means when working with primitives such as booleans or numbers, they won't come through in that way and need to be coerced into their primitive type using a bindable setter or specifying the bindable type explicitly using bindable coercion.
The @bindable decorator signals to Aurelia that a property is bindable in our custom element. Let's create a custom element where we define two bindable properties.
import { bindable } from 'aurelia';
export class NameComponent {
@bindable firstName = '';
@bindable lastName = '';
}<p>Hello ${firstName} ${lastName}. How are you today?</p>You can then use the component in this way,`<name-component first-name="John" last-name="Smith"></name-component>
By default, Aurelia will call a change callback (if it exists) which takes the bindable property name followed by Changed added to the end. For example, firstNameChanged(newVal, previousVal) would fire every time the firstName bindable property is changed.
Due to the way the Aurelia binding system works, change callbacks will not be fired upon initial component initialization. If you worked with Aurelia 1, this behavior differs from what you might expect.
If you would like to call your change handler functions when the component is initially bound (like v1), you can achieve this the following way:
import { bindable } from 'aurelia';
export class NameComponent {
@bindable firstName = '';
@bindable lastName = '';
bound() {
this.firstNameChanged(this.firstName, undefined);
}
firstNameChanged(newVal, oldVal) {
console.log('Value changed');
}
}Like almost everything in Aurelia, you can configure how bindable properties work.
You can specify the binding mode using the mode property and passing in a valid BindingMode to it; @bindable({ mode: BindingMode.twoWay}) - this determines which way changes flow in your binding. By default, this will be BindingMode.oneWay
You can change the name of the callback that is fired when a change is made @bindable({ callback: 'propChanged' })
import { bindable } from 'aurelia';
export class NameComponent {
@bindable({ mode: BindingMode.twoWay}) firstName = '';
@bindable({ callback: 'lnameChanged' }) lastName = '';
lnameChanged(val) {}
}Bindable properties support many different binding modes determining the direction the data is bound in and how it is bound.
By default, bindable properties will be one-way binding. This means values flow into your component but not back out of it (hence the name, one way).
import { bindable, BindingMode } from 'aurelia';
export class Loader {
@bindable({ mode: BindingMode.oneWay })
}Unlike the default, the two-way binding mode allows data to flow in both directions. If the value is changed with your component, it flows back out.
import { bindable, BindingMode } from 'aurelia';
export class Loader {
@bindable({ mode: BindingMode.twoWay})
}Much like most facets of binding in Aurelia, two-way binding is intuitive. Instead of .bind you use .two-way if you need to be explicit, but in most instances, you will specify the type of binding relationship a bindable property is using with @bindable instead.
Explicit two-way binding looks like this:
<input type="text" value.two-way="myVal">The myVal variable will get a new value whenever the text input is updated. Similarly, if myVal were updated from within the view model, the input would get the updated value.
In some cases, you want to make an impact on the value that is binding. For such a scenario, you can use the possibility of new set.
@bindable({
set: value => someFunction(value), /* HERE */
// Or set: value => value,
mode: /* ... */
})Suppose you have a carousel component in which you want to enable navigator feature for it.
<!-- Enable -->
<my-carousel navigator.bind="true">
<my-carousel navigator="true">
<my-carousel navigator=true>
<my-carousel navigator>
<!-- Disable -->
<my-carousel navigator.bind="false">
<my-carousel navigator="false">
<my-carousel navigator=false>
<my-carousel>In version two, you can easily implement such a capability with the set feature.
Define your property like this:
@bindable({ set: /* ? */, mode: BindingMode.toView }) public navigator: boolean = false;For set part, we need functionality to check the input. If the value is one of the following, we want to return true, otherwise, we return the false value.
'': No input for a standalone navigator property.
true: When the navigator property set to true.
"true": When the navigator property set to "true".
So our function will be like this
export function truthyDetector(value: unknown) {
return value === '' || value === true || value === "true";
}Now, we should set truthyDetector function as follows:
@bindable({ set: truthyDetector, mode: BindingMode.toView }) public navigator: boolean = false;Although, there is another way to write the functionality too:
@bindable({ set: v => v === '' || v === true || v === "true", mode: BindingMode.toView }) public navigator: boolean = false;You can simply use any of the above four methods to enable/disable your feature. As you can see, set can be used to transform the values being bound into your bindable property and offer more predictable results when dealing with primitives like booleans and numbers.
By default, you'll find yourself work with binable and field most of the time, like the examples given above. But there' cases where it makes sense to have bindable as a getter, or a pair of getter/setter to do more logic when get/set.
For example, a component card nav that allow parent component to query its active status. With bindable on field, it would be written like this:
@customElement({ name: 'card-nav', template })
export class CardNav implements ICustomElementViewModel {
@bindable routes: RouteLink[] = [];
@bindable({ mode: BindingMode.fromView }) active?: string;
bound() {
this.setActive();
}
setActive() {
this.active = this.routes.find((y) => y.isActive)?.path;
}
handleClick(route: RouteLink) {
this.routes.forEach((x) => (x.isActive = x === route));
this.setActive();
}
}Note that because active value needs to computed from other variables, we have to "actively" call setActive. It's not a big deal, but sometimes not desirable.
For cases like this, we can turn active into a getter, and decorate it with bindable, like the following:
@customElement({ name: 'card-nav', template })
export class CardNav implements ICustomElementViewModel {
@bindable routes: RouteLink[] = [];
@bindable({ mode: BindingMode.fromView }) get active() {
return this.routes.find((y) => y.isActive)?.path;
}
handleClick(route: RouteLink) {
this.routes.forEach((x) => (x.isActive = x === route));
}
}Simpler, since the value of active is computed, and observed based on the properties/values accessed inside the getter.
The bindable setter section shows how to adapt the value is bound to a @bindable property. One common usage of the setter is to coerce the values that are bound from the view. Consider the following example.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable public num: number;
}@customElement({ name:'my-app', template: '<my-el num="42"></my-el>' })
export class MyApp { }Without any setter for the @bindable num we will end up with the string '42' as the value for num in MyEl. You can write a setter to coerce the value. However, it is a bit annoying to write setters for every @bindable.
To address this issue, Aurelia 2 supports type coercion. To maintain backward compatibility, automatic type coercion is disabled by default and must be enabled explicitly.
new Aurelia()
.register(
StandardConfiguration
.customize((config) => {
config.coercingOptions.enableCoercion = true;
// config.coercingOptions.coerceNullish = true;
}),
...
);There are two relevant configuration options.
enableCoercion
The default value is false; that is Aurelia 2 does not coerce the types of the @bindable by default. It can be set to true to enable the automatic type-coercion.
coerceNullish
The default value is false; that is Aurelia2 does not coerce the null and undefined values. It can be set to true to coerce the null and undefined values as well. This property can be thought of as the global counterpart of the nullable property in the bindable definition (see Coercing nullable values section).
Additionally, depending on whether you are using TypeScript or JavaScript for your app, there can be several ways to use automatic type coercion.
For TypeScript development, this gets easier when the emitDecoratorMetadata configuration property in tsconfig.json is set to true. When this property is set, and the @bindable properties are annotated with types, there is no need to do anything else; Aurelia 2 will do the rest.
If, for some reason, you cannot do that, then refer to the next section.
For JavaScript development, you need to specify the explicit type in the @bindable definition.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable({ type: Number }) num;
}Currently, coercing four primitive types are supported out of the box. These are number, string, boolean, and bigint. The coercion functions for these types are respectively Number(value), String(value), Boolean(value), and BigInt(value).
Be mindful when dealing with bigint as the BigInt(value) will throw if the value cannot be converted to bigint; for example null, undefined, or non-numeric string literal.
It is also possible to coerce values into instances of classes. There are two ways how that can be done.
coerce methodYou can define a static method named coerce in the class used as a @bindable type. This method will be called by Aurelia2 automatically to coerce the bound value.
This is shown in the following example with the Person class.
export class Person {
public constructor(
public readonly name: string,
public readonly age: number,
) { }
public static coerce(value: unknown): Person {
if (value instanceof Person) return value;
if (typeof value === 'string') {
try {
const json = JSON.parse(value) as Person;
return new this(json.name, json.age);
} catch {
return new this(value, null!);
}
}
if (typeof value === 'number') {
return new this(null!, value);
}
if (typeof value === 'object' && value != null) {
return new this((value as any).name, (value as any).age);
}
return new this(null!, null!);
}
}import { Person } from './person.ts';
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable public person: Person;
}@customElement({ name:'my-app', template: '<my-el person="john"></my-el>' })
export class MyApp { }According to the Person#coercer implementation, for the example above MyEl#person will be assigned an instance of Person that is equivalent to new Person('john', null).
@coercer decoratorAurelia2 also offers a @coercer decorator to declare a static method in the class as the coercer. The previous example can be rewritten as follows using the @coercer decorator.
import { coercer } from '@aurelia/runtime-html';
export class Person {
public constructor(
public readonly name: string,
public readonly age: number,
) { }
@coercer
public static createFrom(value: unknown): Person {
if (value instanceof Person) return value;
if (typeof value === 'string') {
try {
const json = JSON.parse(value) as Person;
return new this(json.name, json.age);
} catch {
return new this(value, null!);
}
}
if (typeof value === 'number') {
return new this(null!, value);
}
if (typeof value === 'object' && value != null) {
return new this((value as any).name, (value as any).age);
}
return new this(null!, null!);
}
}import { Person } from './person.ts';
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable public person: Person;
}@customElement({ name:'my-app', template: '<my-el person="john"></my-el>' })
export class MyApp { }With the @coercer decorator, you are free to name the static method as you like.
To maintain backward compatibility, Aurelia2 does not attempt to coerce null and undefined values. We believe that this default choice should avoid unnecessary surprises and code breaks when migrating to newer versions of Aurelia.
However, you can explicitly mark a @bindable to be not nullable.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable({ nullable: false }) public num: number;
}When nullable is set to false, Aurelia2 will try to coerce the null and undefined values.
set and auto-coercionIt is important to note that an explicit set (see bindable setter) function is always prioritized over the type. In fact, the auto-coercion is the fallback for the set function. Hence whenever set is defined, the auto-coercion becomes non-operational.
However, this gives you an opportunity to:
Override any of the default primitive type coercing behavior, or
Disable coercion selectively for a few selective @bindable by using a noop function for set.
When using TypeScript, usages of union types are not rare. However, using union types for @bindable will deactivate the auto-coercion.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable public num: number | string;
}For the example above, the type metadata supplied by TypeScript will be Object disabling the auto-coercion.
To coerce union types, you can explicitly specify a type.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable({type: String}) public num: number | string;
}However, using a setter would be more straightforward to this end.
@customElement({ name:'my-el', template: 'not important' })
export class MyEl {
@bindable({set(v: unknown) {... return coercedV;}}) public num: number | string;
}Attribute transferring is a way to relay the binding(s) on a custom element to its child element(s).
As an application grows, the components inside it also grow. Something that starts simple, like the following component
export class FormInput {
@bindable label
@bindable value
}with the template
<label>${label}
<input value.bind="value">
</label>can quickly grow out of hand with a number of needs for configuration: aria, type, min, max, pattern, tooltip, validation etc...
After a while, the FormInput component above will become more and more like a relayer to transfer the bindings from outside, to the elements inside it. This often results in an increase in the number of @bindable. While this is fine, you end up with components that have a lot of boilerplate.
export class FormInput {
@bindable label
@bindable value
@bindable type
@bindable tooltip
@bindable arias
@bindable etc
}And the usage of our component would look like this:
<form-input
label.bind="label"
value.bind="message"
tooltip.bind="Did you know Aurelia syntax comes from an idea of an Angular community member? We greatly appreciate Angular and its community for this."
validation.bind="...">to be repeated like this inside:
<label>${label}
<input value.bind tooltip.bind validation.bind min.bind max.bind>
</label>To juggle all the relevant pieces for such a task isn't difficult, but somewhat tedious. With attribute transferring, which is roughly close to object spreading in JavaScript, the above template should be as simple as:
<label>${label}
<input ...$attrs>
</label>, which reads like this: for some bindings on <form-input>, change the targets of those bindings to the <input> element inside it.
To transfer attributes & bindings from a custom element, there are two steps:
Set capture to true on a custom element via @customElement decorator:
@customElement({
...,
capture: true
})Or use the capture decorator from aurelia package if you don't want to declare the customElement decorator and have to specify your name and template values.
import { capture } from 'aurelia';
@capture
export class MyCustomElement {
...
}
// either form is valid
@capture()
export class MyCustomElement {
...
}As the name suggests, this is to signal the template compiler that all the bindings & attributes, with some exceptions, should be captured for future usage.
Spread the captured attributes onto an element
Using the ellipsis syntax which you might be accustomed to from Javascript, we can spread our attributes onto an element proceeding the magic variable $attrs
<input ...$attrs>Spread attributes and overriding specific ones
In case you want to spread all attributes while explicitly overriding individual ones, make sure these come after the spread operator.
<input value.bind="..." ...$attrs> spread wins
<input ...$attrs value.bind="..."> explicit winsIt's recommended that this feature should not be overused in multi-level capturing & transferring. This is often known as prop-drilling in React and could have a bad effect on the overall & long-term maintainability of an application. It's probably healthy to limit the max level of transferring to 2.
Aurelia conventions enable the setting of capture metadata from the template via <capture> tag, like the following example:
<capture>
<input ...$attrs>Sometimes it is desirable to capture only certain attributes on a custom element. Aurelia supports this via 2nd form of the custom element capture value: a function that takes 1 parameter, which is the attribute name, and returns a boolean to indicate whether it should be captured.
@customElement({
capture: attr => attr !== 'class'
})What attributes are captured
Everything except the template controller and custom element bindables are captured.
export class FormInput {
@bindable label
}A usage example is as follows:
<form-input
if.bind="needsComment"
label.bind="label"
value.bind="extraComment"
class="form-control"
style="background: var(--theme-purple)"
tooltip="Hello, ${tooltip}">What is captured:
value.bind="extraComment"
class="form-control"
style="background: var(--theme-purple)"
tooltip="Hello, ${tooltip}"
What is not captured:
if.bind="needsComment" (if is a template controller)
label.bind="label" (label is a bindable property)
How will attributes be applied in ...$attrs
Attributes that are spread onto an element will be compiled as if it was declared on that element.
This means .bind command will work as expected when it's transferred from some element onto some element that uses .two-way for .bind.
It also means that spreading onto a custom element will also work: if a captured attribute targets a bindable property of the applied custom element. An example:
app.html
<input-field value.bind="message">
input-field.html
<my-input ...$attrs>if value is a bindable property of my-input, the end result will be a binding that connects the message property of the corresponding app.html view model with <my-input> view model value property. The binding mode is also preserved like normal attributes.
Handling forms and user input is quite a common task in applications. Whether you are building a login form, data entry, or even a chat application, Aurelia allows you to work with forms intuitively.
In Aurelia, the binding system uses two-way binding as a default for form elements. Text inputs, text areas and even contenteditable elements all use a two-way binding.
In Aurelia, form elements are reactive, and their changes are directly tied to the underlying view model. Updates flow from the view to the view model, and updates from the view model flow to the view (hence, two-way).
To illustrate how two-way binding works in forms, let's break down the workflow:
The user types a value into the input element. The element is for a first name, so they enter John.
The native form input events are fired, and Aurelia also sees the value has changed.
The binding system sees the new value and notifies the view model to update the value.
Any reference to the bound value will be updated without needing any callback functions or additional notification steps (the value changes).
Creating forms in Aurelia requires no special configuration or treatment. Create a form element and add form input controls with bindings. Here is a basic form example for a login form to show you how little code you need.
Firstly, let's create the markup for our login form:
<form submit.trigger="handleLogin()">
<div>
<label for="email">Email:</label>
<input id="email" type="text" value.bind="email">
</div>
<div>
<label for="password">Password:</label>
<input id="password" type="password" value.bind="password">
</div>
<button type="submit">Login</button>
</form>Before we write the view model code, let's break down what we did here:
We created a form with two text inputs
We used value.bind to bind the native value attribute of these fields to the corresponding view model properties
We are calling a function handleLogin when the submit event on the form is triggered to handle the bindable properties inside
Now, the corresponding view model code:
export class LoginComponent {
private email = '';
private password = '';
// This function is called when the form is submitted
handleLogin() {
// Call an API/validate the bound values
}
}There is not a whole lot of code here for what is happening. Whenever the email or password values change, they will be reflected inside of our view model. Inside the handleLogin method, we would probably validate the data and call an API.
Using submit.trigger on a form will prevent its default action by applying a event.preventDefault behind-the-scenes. This means your form will not submit to the action or method attributes on the form, you will need to handle this manually.
Binding to text inputs uses a syntax similar to binding to other elements in Aurelia. By default, input elements will use two-way binding, which means the value will update in the view when changed inside the view model and updated in the view model when changed in the view.
<form>
<label>User value</label><br>
<input type="text" value.bind="userValue" />
</form>You can even bind to other attributes on form elements such as the placeholder attribute.
<form>
<label>User value</label><br>
<input type="text" value.bind="userValue" placeholder.bind="myPlaceholder" />
</form>A textarea element is just like any other form element. It allows you to bind to its value and, by default, value.bind will be two-way binding (meaning changes flow from out of the view into the view model and changes in the view-model flow back to the view).
<form role="form">
<textarea value.bind="textAreaValue"></textarea>
</form>Aurelia supports the two-way binding of various data types to checkbox input elements.
Bind a boolean property to an input element's checked attribute using checked.bind="myBooleanProperty".
export class App {
motherboard = false;
cpu = false;
memory = false;
}<template>
<form>
<h4>Products</h4>
<label><input type="checkbox" checked.bind="motherboard"> Motherboard</label>
<label><input type="checkbox" checked.bind="cpu"> CPU</label>
<label><input type="checkbox" checked.bind="memory"> Memory</label>
motherboard = ${motherboard}<br>
cpu = ${cpu}<br>
memory = ${memory}<br>
</form>
</template>A set of checkbox elements is a multiple-selection interface. If you have an array that serves as the "selected items" list, you can bind the array to each input's checked attribute. The binding system will track the input's checked status, adding the input's value to the array when the input is checked and removing the input's value from the array when the input is unchecked.
To define the input's "value", bind the input's model attribute: model.bind="product.id".
export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProductIds = [];
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="checkbox" model.bind="product.id" checked.bind="selectedProductIds">
${product.id} - ${product.name}
</label>
<br>
Selected product IDs: ${selectedProductIds}
</form>
</template>Numbers aren't the only type of value you can store in a "selected items" array. The binding system supports all types, including objects. Here's an example that adds and removes "product" objects from a selectedProducts array using the checkbox data-binding.
export interface IProduct {
id: number;
name: string;
}
export class App {
products: IProduct[] = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProducts: IProduct[] = [];
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="checkbox" model.bind="product" checked.bind="selectedProducts">
${product.id} - ${product.name}
</label>
Selected products:
<ul>
<li repeat.for="product of selectedProducts">${product.id} - ${product.name}</li>
</ul>
</form>
</template>You may run into situations where the object your input element's model is bound to do not have reference equality to any objects in your checked array. The objects might match by id, but they may not be the same object instance. To support this scenario, you can override Aurelia's default "matcher", which is an equality comparison function that looks like this: (a, b) => a === b.
You can substitute your chosen function with the right logic to compare your objects.
export class App {
selectedProducts = [
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' }
];
productMatcher = (a, b) => a.id === b.id;
}<template>
<form>
<h4>Products</h4>
<label>
<input type="checkbox" model.bind="{ id: 0, name: 'Motherboard' }"
matcher.bind="productMatcher"
checked.bind="selectedProducts">
Motherboard
</label>
<label>
<input type="checkbox" model.bind="{ id: 1, name: 'CPU' }"
matcher.bind="productMatcher"
checked.bind="selectedProducts">
CPU
</label>
<label>
<input type="checkbox" model.bind="{ id: 2, name: 'Memory' }"
matcher.bind="productMatcher"
checked.bind="selectedProducts">
Memory
</label>
Selected products:
<ul>
<li repeat.for="product of selectedProducts">${product.id} - ${product.name}</li>
</ul>
</form>
</template>Finally, here's an example that adds and removes strings from an selectedProducts array using the checkbox data-binding. This is example is unique because it does not use model.bind to assign each checkbox's value. Instead, the input's standard value attribute is used.
Normally we cannot use the standard value attribute in conjunction with checked binding because it coerces anything assigned to a string. This example uses an array of strings, so everything works just fine.
export class App {
products = ['Motherboard', 'CPU', 'Memory'];
selectedProducts = [];
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="checkbox" value.bind="product" checked.bind="selectedProducts">
${product}
</label>
<br>
Selected products: ${selectedProducts}
</form>
</template>A radio input group is a "single select" interface. Aurelia supports two-way binding any type of property to a group of radio inputs. The examples below illustrate binding number, object, string and boolean properties to sets of radio inputs. In each of the examples, there's a common set of steps:
Group the radios via the name property. Radio buttons with the same value for the name attribute are in the same "radio button group"; only one radio button in a group can be selected at a time.
Define each radio's value using the model property.
Two-way bind each radio's checked attribute to a "selected item" property on the view model.
Let's start with an example that uses a numeric "selected item" property. Each radio input will be assigned a number value via the model property in this example. Selecting a radio will cause its model value to be assigned to the selectedProductId property.
export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProductId = null;
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="radio" name="group1"
model.bind="product.id" checked.bind="selectedProductId">
${product.id} - ${product.name}
</label>
<br>
Selected product ID: ${selectedProductId}
</form>
</template>The binding system supports binding all types of radios, including objects. Here's an example that binds a group of radios to a selectedProduct object property.
export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProduct = null;
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="radio" name="group2"
model.bind="product" checked.bind="selectedProduct">
${product.id} - ${product.name}
</label>
Selected product: ${selectedProduct.id} - ${selectedProduct.name}
</form>
</template>You may run into situations where the object your input element's model is bound to does not have reference equality to any of the objects in your checked attribute bound to. The objects might match by id, but they may not be the same object instance. To support this scenario, you can override Aurelia's default "matcher", which is an equality comparison function that looks like this: (a, b) => a === b.
You can substitute your chosen function with the right logic to compare your objects.
export class App {
selectedProduct = { id: 1, name: 'CPU' };
productMatcher = (a, b) => a.id === b.id;
}<template>
<form>
<h4>Products</h4>
<label>
<input type="radio" name="group3"
model.bind="{ id: 0, name: 'Motherboard' }"
matcher.bind="productMatcher"
checked.bind="selectedProduct">
Motherboard
</label>
<label>
<input type="radio" name="group3"
model.bind="{ id: 1, name: 'CPU' }"
matcher.bind="productMatcher"
checked.bind="selectedProduct">
CPU
</label>
<label>
<input type="radio" name="group3"
model.bind="{ id: 2, name: 'Memory' }"
matcher.bind="productMatcher"
checked.bind="selectedProduct">
Memory
</label>
Selected product: ${selectedProduct.id} - ${selectedProduct.name}
</form>
</template>In this example, each radio input is assigned one of three literal values: null, true and false. Selecting one of the radios will assign its value to the likesCake property.
export class App {
likesCake = null;
}<template>
<form>
<h4>Do you like cake?</h4>
<label>
<input type="radio" name="group3"
model.bind="null" checked.bind="likesCake">
Don't Know
</label>
<label>
<input type="radio" name="group3"
model.bind="true" checked.bind="likesCake">
Yes
</label>
<label>
<input type="radio" name="group3"
model.bind="false" checked.bind="likesCake">
No
</label>
likesCake = ${likesCake}
</form>
</template>Finally, here's an example using strings. This is example is unique because it does not use model.bind to assign each radio's value. Instead, the input's standard value attribute is used. Normally we cannot use the standard value attribute in conjunction with checked binding because it coerces anything assigned to a string.
export class App {
products = ['Motherboard', 'CPU', 'Memory'];
selectedProduct = null;
}<template>
<form>
<h4>Products</h4>
<label repeat.for="product of products">
<input type="radio" name="group4"
value.bind="product" checked.bind="selectedProduct">
${product}
</label>
<br>
Selected product: ${selectedProduct}
</form>
</template>A <select> element can serve as a single-select or multiple-select "picker", depending on whether the multiple attribute is present. The binding system supports both use cases. The samples below demonstrate a variety of scenarios.
All use a common series of steps to configure the selected element:
Add a <select> element to the template and decide whether the multiple attribute should be applied.
Bind the select element's value attribute to a property. In "multiple" mode, the property should be an array. In singular mode, it can be any type.
Define the select element's <option> elements. You can use repeat or add each option element manually.
Specify each option's value via the model property:
<option model.bind="product.id">${product.name}</option>
You can use the standard value attribute instead of model, remember- it will coerce anything it's assigned to a string.
export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProductId = null;
}<template>
<label>
Select product:<br>
<select value.bind="selectedProductId">
<option model.bind="null">Choose...</option>
<option repeat.for="product of products"
model.bind="product.id">
${product.id} - ${product.name}
</option>
</select>
</label>
Selected product ID: ${selectedProductId}
</template>export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProduct = null;
}<template>
<label>
Select product:<br>
<select value.bind="selectedProduct">
<option model.bind="null">Choose...</option>
<option repeat.for="product of products"
model.bind="product">
${product.id} - ${product.name}
</option>
</select>
</label>
Selected product: ${selectedProduct.id} - ${selectedProduct.name}
</template>You may run into situations where the object to your select element's value is bound and does not have reference equality with any of the objects your option element model properties are bound to. The select's value object might "match" one of the option objects by id, but they may not be the same object instance.
To support this scenario, you can override Aurelia's default "matcher", which is an equality comparison function that looks like this: (a, b) => a === b. You can substitute your chosen function with the right logic to compare your objects.
export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
productMatcher = (a, b) => a.id === b.id;
selectedProduct = { id: 1, name: 'CPU' };
}<template>
<label>
Select product:<br>
<select value.bind="selectedProduct" matcher.bind="productMatcher">
<option model.bind="null">Choose...</option>
<option repeat.for="product of products"
model.bind="product">
${product.id} - ${product.name}
</option>
</select>
</label>
Selected product: ${selectedProduct.id} - ${selectedProduct.name}
</template>export class App {
likesTacos = null;
}<template>
<label>
Do you like tacos?:
<select value.bind="likesTacos">
<option model.bind="null">Choose...</option>
<option model.bind="true">Yes</option>
<option model.bind="false">No</option>
</select>
</label>
likesTacos: ${likesTacos}
</template>export class App {
products = ['Motherboard', 'CPU', 'Memory'];
selectedProduct = '';
}<template>
<label>
Select product:<br>
<select value.bind="selectedProduct">
<option value="">Choose...</option>
<option repeat.for="product of products"
value.bind="product">
${product}
</option>
</select>
</label>
Selected product: ${selectedProduct}
</template>export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProductIds = [];
}<template>
<label>
Select products:
<select multiple value.bind="selectedProductIds">
<option repeat.for="product of products"
model.bind="product.id">
${product.id} - ${product.name}
</option>
</select>
</label>
Selected product IDs: ${selectedProductIds}
</template>export class App {
products = [
{ id: 0, name: 'Motherboard' },
{ id: 1, name: 'CPU' },
{ id: 2, name: 'Memory' },
];
selectedProducts = [];
}<template>
<label>
Select products:
<select multiple value.bind="selectedProducts">
<option repeat.for="product of products"
model.bind="product">
${product.id} - ${product.name}
</option>
</select>
</label>
Selected products:
<ul>
<li repeat.for="product of selectedProducts">${product.id} - ${product.name}</li>
</ul>
</template>export class App {
products = ['Motherboard', 'CPU', 'Memory'];
selectedProducts = [];
}<template>
<label>
Select products:
<select multiple value.bind="selectedProducts">
<option repeat.for="product of products"
value.bind="product">
${product}
</option>
</select>
</label>
Selected products: ${selectedProducts}
</template>Most of the time, a <form> element should be used to group one or many controls in a form. It acts as a container for those controls and can also be used for layout purposes with CSS.
Normally, HTML forms can be submitted without involving any JavaScript via the action and method attributes on a <form>. Though it's also common in applications that forms are driven by JavaScript.
In Aurelia, driving form via script can be achieved via submit event on the form, with the basic usage looking like the following example:
<form submit.trigger="submitMyForm()">
...
</form>class MyApp {
submitMyForm() {
fetch('/register', { method: 'POST', ... })
}
}Note that by default, for a <form/> without a method attribute, or method attribute value being equal to GET/get, using submit.trigger will call preventDefault() on the submit event, which prevents the normally unwanted behavior of html of navigating the page to the URI of the form. If this behavior is not desired, return true in the method being called, like the following example:
class MyApp {
submitMyForm() {
...
return true;
}
}Validation is an important part of creating good forms. Aurelia provides a robust validation plugin that allows you to validate forms, create custom validation rules and configure every facet of validation in your Aurelia applications.
To learn about form validation using the Aurelia Validation package, please consult the validation documentation below for details.
Learn about viewports in Router-Lite and how to configure hierarchical routing.
The <au-viewport> element, or commonly referred to as viewport (not to confuse with viewport meta tag), is the "outlet", where the router-lite attaches/loads the components. For a basic example of viewport, please refer the "Getting started"-tutorial. Most of the examples in the preceding sections show the usage of only a single viewport. However, you can use multiple viewports with the sibling viewports and hierarchical routing. These are useful to create different routing layouts. In the subsequent sections, we first discuss about that. Later in this part of the documentation, we focus on the different configuration options available for viewports.
As seen in the "Getting started"-tutorial, a component can define a set of children routes (using either the @route decorator or the static properties). The child routes can also in turn define children routes of there own. Such route configuration are commonly known as hierarchical route configuration.
To understand it better, let us consider an example. We want to show a list of products, as links, and when a product link is clicked, we display the details of the product.
+--------------------------------------------------------------------+
| |
| Root-Viewport |
| + |
| | |
| | +---------------------------------------------------------+ |
| +->+ | |
| | Products | |
| | | |
| | +-------------+ Child-Viewport | |
| | + | |
| | +-------------+ | | |
| | | +--------------------------+ | |
| | +-------------+ +->+ | | |
| | | Product details | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | +--------------------------+ | |
| +---------------------------------------------------------+ |
+--------------------------------------------------------------------+
To this end we want a viewport on the root component which is used to host the list component. The list component itself houses anther viewport, or more accurately a child viewport, which is then used to host the product details.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
import { Products } from './products';
@route({
routes: [
{ path: '', redirectTo: 'products' },
{
path: 'products',
component: Products,
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}<nav>
<a load="products">Products</a>
</nav>
<au-viewport></au-viewport> <!-- the root viewport -->The route configuration for the root component consists of a single root for the list component and it also houses a single viewport. The Products component defines its own child route configuration and houses a child viewport. This is shown below.
import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
import { Product } from './product';
import { IProductService, ProductDetail } from './product-service';
import template from './products.html';
// child route configuration
@route({
routes: [
{
id: 'product',
path: ':id/details',
component: Product,
},
],
})
@customElement({ name: 'pro-ducts', template })
export class Products {
promise: Promise<ProductDetail[]>;
public constructor(@IProductService productService: IProductService) {
this.promise = productService.getAll();
}
}<style>
div.content {
display: flex;
gap: 1rem;
padding: 1rem;
}
</style>
<div class="content">
<div promise.bind="promise">
<span pending>Fetching products...</span>
<div then.bind="data">
Fetched ${data.length} products
<ul>
<li repeat.for="item of data">
<a href="${item.id}/details">${item.title}</a>
</li>
</ul>
</div>
</div>
<au-viewport></au-viewport> <!-- the child viewport -->
</div>The IProductService injected to the Products is just some service used to populate the product list and has very little relevance to the discussion related to the router. And the extra style is added to display the list and the details side by side. And that's pretty much all you need for a simple hierarchical routing configuration. You can see this in action below.
If you open the example in a new tab, you can see how the URL paths are constructed. For example, when you click a product link, the URL is /42/details or /products/42/details. This also means that when you try to navigate to that URL directly, the product details will be loaded from the start. It essentially creates shareable URLs.
Two viewports are called siblings if they are under one parent routing hierarchy. Let us recreate the previous example but using sibling viewports this time.
+--------------------------------------------------------------------+
| |
| Viewport#1 Viewport#2 |
| + + |
| | | |
| | +------------------------+ | +------------------------+ |
| +->+ | +->+ | |
| | Products' List | | Product details | |
| | | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| | +-------------+ | | | |
| | | | | |
| +------------------------+ +------------------------+ |
+--------------------------------------------------------------------+To this end, we want to viewports, housed side-by-side on the root component. We show the products' list on one viewport and the details of the selected product on the other one.
To this end, let us start with the routing configuration on the root component.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
import { Products } from './products';
import { Product } from './product';
@route({
routes: [
{
id: 'products',
path: ['', 'products'],
component: Products,
},
{
id: 'details',
path: 'details/:id',
component: Product,
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}Two routes, one for the list another for the details, are configured on the route. Next we need 2 viewports to on the root component. Let us get that done.
<style>
div.content {
display: flex;
gap: 1rem;
padding: 1rem;
}
</style>
<nav>
<a load="products">Products</a>
</nav>
<div class="content">
<au-viewport></au-viewport>
<au-viewport></au-viewport>
</div>Even though we are not yet done, you can check out our work so far in the live example below.
If you run the example, you can immediately see a "problem" that both the viewports are loading the products' list. Although it is not an error per se, with natural use-case in mind, you probably like to avoid that. Let us fix this "problem" first.
This is happening due to the default value of the default attribute of the <au-viewport> that is set to '' (empty string). This default value enables loading the component associated with the empty path without any additional configuration. This default behavior makes sense as the usage of a single viewport at every routing hierarchy might be prevalent.
However, we need a way to prevent this duplication. To this end, we can bind null to the default attribute of a viewport, which instructs the router-lite that this particular viewport should be left out when it is empty (that is no component is targeted to be loaded in this viewport).
<div class="content">
- <au-viewport></au-viewport>
- <au-viewport></au-viewport>
+ <!-- instruct the router to load the products component by default -->
+ <au-viewport default="products"></au-viewport>
+ <au-viewport default.bind="null"></au-viewport>
</div>You can see in the live example below that this fixes the duplication issue.
We still need a way to load the product details on the second viewport. Note that till now, the two viewports cannot be referentially differentiated from one another; that is if you want to load a component specifically on the first or on the second viewport, there is no way to do this for now. To this end, we need to name the viewports.
<div class="content">
- <au-viewport></au-viewport>
- <au-viewport default.bind="null"></au-viewport>
+ <au-viewport name="list" default="products"></au-viewport>
+ <au-viewport name="details" default.bind="null"></au-viewport>
</div>Although we name the viewports semantically, it is not necessary, and you are free to choose viewport names, as you like. Lastly, we need to use the load attribute in the Products component to construct the URL, or more accurately the routing instruction correctly, such that the details of the product is loaded on the details viewport.
<ul>
<li repeat.for="item of data">
- <a href="#">${item.title}</a>
+ <a load="route.bind:{component:'details', params: {id: item.id}, viewport:'details'}; context.bind:null">${item.title}</a>
</li>
</ul>Using the load attribute we are instructing the router-lite to load the Product (using the route-id details) component, with the id parameter of the route set to the id of the current item in the repeater, in the details viewport. With the context.bind:null, we are instructing the router-lite to perform this routing instruction on the root routing context (refer the documentation for the load attribute for more details). Now, when someone clicks a product link the associated details are loaded in the details viewport. You can see this in action below.
If you open the example in a new tab, you can see how the URL paths are constructed. For example, when you click a product link, the URL is /details/42@details+products@list.
As seen in the sibling viewports example, viewports can be named. It is particularly useful when there are multiple sibling viewports present. Note that specifying a value for the name attribute of viewport is optional, and the default value is simply 'default'.
In the following example, we have the main viewport for our main content and then another viewport called sidebar for our sidebar content.
<main>
<au-viewport name="main"></au-viewport>
</main>
<aside>
<au-viewport name="sidebar"></au-viewport>
</aside>The names can be used to instruct the router-lite to load a specific component to a specific named viewport. To this end the path syntax is as follows:
{path}@{viewport-name}The live example below shows this.
Note the load attributes in the anchor elements.
<a load="products@list+details/${id}@details">Load products@list+details/${id}@details</a>
<a load="details/${id}@details">Load details/${id}@details</a>In the example, clicking the first anchor loads the products component in the list viewport and the details of the product with #{id} into the details viewport. The second anchor facilitates loading only the the details of the product with #{id} into the details viewport.
By default, the routes/components are loaded into the first available viewport, when there is no viewport instruction is present. However, the routes can also be configured, such that a configured route is allowed to be loaded only in a certain viewport. This is useful when you know that a certain component needs to be loaded in a certain viewport, because in that case you can use the simple {path} instruction instead of the more verbose alternative, the {path}@{viewport-name} instruction. To this end, use the viewport option of the route configuration.
import { route } from '@aurelia/router-lite';
import { Products } from './products';
import { Product } from './product';
@route({
routes: [
{
id: 'products',
path: 'products',
component: Products,
viewport: 'list',
},
{
id: 'details',
path: 'details/:id',
component: Product,
viewport: 'details',
},
],
})
export class MyApp {}In this example, we are specifying that the Products component needs to be loaded into the list viewport and the Product component need to be loaded into the details viewport. You can also see this in the live example below.
Note the anchors in the example that show that the viewport names can now be dropped from the routing instructions.
<nav>
<!-- clicking this will load the products into the 'list' viewport -->
<a load="products">products</a>
<!-- clicking this will load the products into the 'list' viewport and the details of product #3 into the 'details' viewport -->
<a load="products+details/3">products+details/3</a>
<!-- same as above; but shows that the sibling order does not matter -->
<a load="details/4+products">details/4+products</a>
</nav>used-byThe used-by attribute on the au-viewport component can be thought of as (almost) the parallel of the viewport configuration option on route configuration. Using this property on a viewport, you can "reserve" a viewport for particular component(s). In other words, you are instructing the router that no other components apart from those specified can be loaded into a viewport with used-by set.
<au-viewport used-by="ce-two"></au-viewport>
<au-viewport used-by="ce-one"></au-viewport>In this example, we are instructing the router-lite to reserve the first viewport for ce-two custom element and the reserve the second viewport for ce-one custom element. You can see this in the live example below, by clicking the links and observing how the components are loaded into the reserved viewports.
You can reserve a viewport for more than one component. To this end, you can use comma-separated values for the used-by attribute.
<au-viewport used-by="ce-one,ce-two"></au-viewport>
<au-viewport used-by="ce-one"></au-viewport>The live example below shows this in action
Although the used-by attribute feels like a markup alternative of the viewport configuration option on route configuration, there is a subtle difference. Having the used-by property on a particular viewport set to X component, does not prevent a preceding viewport without any value for the used-by property to load the X component. This is shown in action in the example below.
Note how clicking the links load the components also in the first viewport without any value for the used-by.
When no route is loaded into a viewport, a 'default' route is loaded into the viewport. For every viewport, such defaults can be configured using the default attribute. It is optional to specify a value for this attribute and the empty string ('') is used as the default value for this property. This explains why the route with empty path (when exists) is loaded into a viewport without the default attribute set, as seen in the sibling viewports example.
Another path can be used to override the default value of the default attribute. The following example shows four viewports with varied values for the default attribute. Whereas the first viewport might be the usual viewport with empty path, the other three specifies different default values. These components are loaded into the viewport, by default when the application is started.
<div class="content">
<!-- loads the empty route -->
<au-viewport></au-viewport>
<!-- loads the ce-two with parameter -->
<au-viewport default="foo/42"></au-viewport>
<!-- loads the ce-one -->
<au-viewport default="ce-one"></au-viewport>
<!-- loads the ce-two without parameter -->
<au-viewport default="foo"></au-viewport>
</div>The example below shows this in action.
Note that default attribute can also be bound to null, to instruct the router-lite not to load any component into ths viewport when no component is scheduled (either by explicit instruction of implicit availability check) to be loaded into the viewport. This is useful when you have more than one viewports and you want to load the empty path (assuming it is configured) in a particular viewport. In that case, you can bind null to the default attribute of the other viewport. To see examples of this, please refer to the sibling viewport section.
If a route cannot be recognized, a fallback route is looked for and loaded (when configured) into the viewport. Such fallback can be configured using the fallback property of the route configuration. au-viewport also offers a similar fallback attribute, using which a fallback component can be configured for a particular viewport. The fallback attribute is similar to its route configuration counterpart, with only one difference. The fallback attribute in the au-viewport, when configured, always takes precedence over the fallback route configuration option. This is shown in the live example below.
A function for the value of fallback is also supported. An example looks like as follows, where the example redirects the user to NF1 component if an attempt to load a path /foo is made. Every other attempt to load an unknown path is results loading the NF2 component.
import { customElement } from '@aurelia/runtime-html';
import {
IRouteContext,
ITypedNavigationInstruction_string,
route,
RouteNode,
ViewportInstruction,
} from '@aurelia/router-lite';
import template from './my-app.html';
@customElement({ name: 'ce-a', template: 'a' })
class A {}
@customElement({ name: 'n-f-1', template: 'nf1' })
class NF1 {}
@customElement({ name: 'n-f-2', template: 'nf2' })
class NF2 {}
@route({
routes: [
{ id: 'r1', path: ['', 'a'], component: A },
{ id: 'r2', path: ['nf1'], component: NF1 },
{ id: 'r3', path: ['nf2'], component: NF2 },
],
})
@customElement({
name: 'my-app',
template: `<nav>
<a href="a">A</a>
<a href="foo">Foo</a>
<a href="bar">Bar</a>
</nav>
<au-viewport fallback.bind></au-viewport>`
})
export class MyApp {
fallback(vi: ViewportInstruction, _rn: RouteNode, _ctx: IRouteContext): string {
return (vi.component as ITypedNavigationInstruction_string).value === 'foo' ? 'r2' : 'r3';
}
}You can also see this in action below.
Learn how to work with slots to work with the concept of dynamic slot placeholders in your custom elements.
In Aurelia, we have two ways to project content into custom elements. In the case of Shadow DOM, we can use <slot> and for situations where Shadow DOM is not desirable, we have <au-slot>
When working with Shadow DOM-enabled components, the <slot> element is a web platform native way to allow content projection into components. In some instances, the <slot> element will not be the right choice, and you will need to consider <au-slot> (referenced below) instead.
The slot element will only work when Shadow DOM is enabled for your component. Attempting to use the slot element with it disabled will throw an error in the console.
In the case of a fictional but realistic example, we have a modal element. The user can provide content which is rendered inside of the element.
<div class="modal">
<div class="modal-inner">
<slot></slot>
</div>
</div>Assuming this is a Shadow DOM-enabled component, all is well. We have a custom element that allows for content to be used inside of it.
Because we named our component au-modal we will then use it like this:
<au-modal>
<div slot>
<p>Modal content inside of the modal</p>
</div>
</au-modal>Notice how we use the attribute slot on our content being passed in? This tells Aurelia to project our content into the default slot. Custom elements can have multiple slots, so how do we tell Aurelia where to project our content?
A named slot is no different to a conventional slot. The only difference is the slot has a name we can reference. A slot without a name gets the name default by default.
<div class="modal">
<div class="modal-inner">
<slot name="content"></slot>
</div>
</div>Now, to use our element with a named slot, you can do this:
<au-modal>
<div slot="name">
<p>Modal content inside of the modal</p>
</div>
</au-modal>A slot can display default content when nothing is explicitly projected into it. Fallback content works for default and named slot elements.
<div class="modal">
<button type="button" data-action="close" class="close" aria-label="Close" click.trigger="close()" ><span aria-hidden="true">×</span></button>
<div class="modal-inner">
<slot>This is the default content shown if the user does not supply anything.</slot>
</div>
</div><slot> element), with the slotchange eventThe <slot> element comes with an event based way to listen to its changes. This can be done via listening to slotchange even on the <slot> element, like the following example:
<slot slotchange.trigger="handleSlotChange($event.target.assignedNodes())"></slot>class MyApp {
handleSlotChange(nodes: Node[]) {
console.log('new nodes are:', nodes);
}
}@children decoratorIn case where it's not desirable to go to listen to projection change at the targets (<slot> elements), it's also possible to listen to projection at the source with @children decorator. Decorating a property on a custom element class with @children decorator will setup mutation observer to notify of any changes, like the following example:
export class MyDetails {
@children('div') divs
}{% code title="my-app.html" overflow="wrap" lineNumbers="true" }
<my-details>
<div>@children decorator is a good way to listen to node changes without having to deal with boilerplate yourself</div>
</my-details>After the initial rendering, myDetails.divs will be an array of 1 <div> element, and any future addition of any <div> elements to the <my-details> element will update the divs property on myDetails instance, with corresponding array.
Additionally, the @children decorator will also call a callback as a reactive change handler. The name of the callback, if omitted in the decorator, will be derived based on the property being decorated, example: divs -> divsChanged
@children decorator usage@children() prop
Use default options, observe mutation, and select all elements
@children('div') prop
Observe mutation, and select only div elements
Aurelia provides another way of content projection with au-slot. This is similar to the native slot when working with content projection. However, it does not use Shadow DOM. au-slot is useful where you want externally defined styles to penetrate the component boundary, facilitating easy styling of components.
Suppose you create your own set of custom elements solely used in your application. In that case, you might want to avoid the native slots in the custom elements, as it might be difficult to style them from your application.
However, if you still want slot-like behavior, then you can use au-slot, as that makes styling those custom elements/components easier. Instead of using shadow DOM, the resulting view is composed purely by the Aurelia compilation pipeline.
There are other aspects of au-slot as well which will be explored in this section with examples.
Like slot, a "projection target"/"slot" can be defined using a <au-slot> element, and a projection to that slot can be provided using a [au-slot] attribute. Consider the following example.
static content
<au-slot>fallback content for default slot.</au-slot>
<au-slot name="s1">fallback content for s1 slot.</au-slot><!-- Usage without projection -->
<my-element></my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
static content
fallback content for default slot.
fallback content for s1 slot.
</my-element>
-->
<!-- Usage with projection -->
<my-element>
<div>d</div> <!-- using `au-slot="default"` explicitly also works. -->
<div au-slot="s1">p1</div>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
static content
<div>d</div>
<div>p1</div>
</my-element>
-->
<my-element>
<template au-slot="s1">p1</template>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
static content
fallback content for default slot.
p1
</my-element>
-->In the example above, the my-element custom element defines two slots: one default and one named. The slots can optionally have fallback content; i.e. when no projection is provided for the slot, the fallback content will be displayed. Projecting to a slot is, therefore, also optional. However, when a projection is provided for a slot, that overrides the fallback content of that slot.
Similar to native shadow DOM and <slot/>/[slot] pair, [au-slot] attribute is not mandatory if you are targeting the default slot. All content without explicit [au-slot] is treated as targeting the default slot. Having no [au-slot] is also equal to having explicit au-slot on the content:
<template as-custom-element="my-element">
<au-slot>dfb</au-slot>
</template>
<my-element><div au-slot>projection</div></my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<div>projection</div>
</my-element>
-->Another important point to note is that the usage of [au-slot] attribute is supported only on the direct children elements of a custom element. This means that the following examples do not work.
<!-- Do NOT work. -->
<div au-slot></div>
<template><div au-slot></div></template>
<my-element>
<div>
<div au-slot></div>
</div>
<my-element>Inject the projected slot information
It is possible to inject an instance of IAuSlotsInfo in a custom element view model. This provides information related to the slots inside a custom element. The information includes only the slot names for which content has been projected. Let's consider the following example.
<au-slot>dfb</au-slot>
<au-slot name="s1">s1fb</au-slot>
<au-slot name="s2">s2fb</au-slot>import { IAuSlotsInfo } from '@aurelia/runtime-html';
class MyElement {
public constructor(
@IAuSlotsInfo public readonly slotInfo: IAuSlotsInfo,
) {
console.log(slotInfo.projectedSlots);
}
}<!-- my_element_instance_1 -->
<my-element>
<div au-slot="default">dp</div>
<div au-slot="s1">s1p</div>
</my-element>
<!-- my_element_instance_2 -->
<my-element></my-element>The followingrk would be logged to the console for the instances of my-element.
// my_element_instance_1
['default', 's1']
// my_element_instance_2
[]It is also possible to use data-binding, interpolation etc., while projecting. While doing so, the scope accessing rule can be described by the following thumb rule:
When the projection is provided, the scope of the custom element providing the projection is used.
When the projection is not provided, the scope of the inner custom element is used.
The outer custom element can still access the inner scope using the $host keyword while projecting.
To further explain how these rules apply, these rules are explained with the following examples.
Let's consider the following example with interpolation.
<my-element>
<div au-slot="s1">${message}</div>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<div>outer</div>
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1">${message}</au-slot>export class MyElement {
public readonly message: string = 'inner';
}Although the my-element has a message property, but as my-app projects to s1 slot, scope of my-app is used to evaluate the interpolation expression. Similar behavior can also be observed when binding properties of custom elements, as shown in the following example.
<my-element>
<foo-bar au-slot="s1" foo.bind="message"></foo-bar>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<foo-bar>outer</foo-bar>
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1">${message}</au-slot>export class MyElement {
public readonly message: string = 'inner';
}${foo}export class FooBar {
@bindable public foo: string;
}Let's consider the following example with interpolation. This is the same example as before, but this time without projection.
<my-element></my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
inner
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1">${message}</au-slot>export class MyElement {
public readonly message: string = 'inner';
}Note that in the absence of projection, the fallback content uses the scope of my-element. For completeness, the following example shows that it also holds while binding values to the @bindables in custom elements.
<my-element></my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<foo-bar>inner</foo-bar>
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1">
<foo-bar foo.bind="message"></foo-bar>
</au-slot>export class MyElement {
public readonly message: string = 'inner';
}${foo}export class FooBar {
@bindable public foo: string;
}$hostThe outer custom element can access the inner custom element's scope using the $host keyword, as shown in the following example.
<my-element>
<div au-slot="s1">${$host.message}</div>
<div au-slot="s2">${message}</div>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<div>inner</div>
<div>outer</div>
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1"></au-slot>
<au-slot name="s2"></au-slot>export class MyElement {
public readonly message: string = 'inner';
}Note that using the $host.message expression, MyApp can access the MyElement#message. The following example demonstrates the same behavior for binding values to custom elements.
<my-element>
<foo-bar au-slot="s1" foo.bind="$host.message"></foo-bar>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<foo-bar>inner</foo-bar>
</my-element>
-->export class MyApp {
public readonly message: string = 'outer';
}<au-slot name="s1"></au-slot>export class MyElement {
public readonly message: string = 'inner';
}${foo}export class FooBar {
@bindable public foo: string;
}Let's consider another example of $host which highlights the communication between the inside and outside of a custom element that employs <au-slot>
<template as-custom-element="my-element">
<bindable name="people"></bindable>
<au-slot name="grid">
<au-slot name="header">
<h4>First Name</h4>
<h4>Last Name</h4>
</au-slot>
<template repeat.for="person of people">
<au-slot name="content" expose.bind="{ person, $event, $odd, $index }">
<div>${person.firstName}</div>
<div>${person.lastName}</div>
</au-slot>
</template>
</au-slot>
</template>
<my-element people.bind="people">
<template au-slot="header">
<h4>Meta</h4>
<h4>Surname</h4>
<h4>Given name</h4>
</template>
<template au-slot="content">
<div>${$host.$index}-${$host.$even}-${$host.$odd}</div>
<div>${$host.person.lastName}</div>
<div>${$host.person.firstName}</div>
</template>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<h4>Meta</h4> <h4>Surname</h4> <h4>Given name</h4>
<div>0-true-false</div> <div>Doe</div> <div>John</div>
<div>1-false-true</div> <div>Mustermann</div> <div>Max</div>
</my-element>
-->export class MyApp {
public readonly people: Person[] = [
new Person('John', 'Doe'),
new Person('Max', 'Mustermann'),
];
}
class Person {
public constructor(
public firstName: string,
public lastName: string,
) { }
}In the example above, we replace the 'content' template of the grid, defined in my-element, from my-app. While doing so, we can grab the scope of the <au-slot name="content" /> and use the properties made available by the binding expose.bind="{ person, $even, $odd, $index }", and use those in the projection template.
Note that $host allows us to access whatever the <au-slot/> element exposes, and this value can be changed to enable powerful scenarios. Without the $host it might not have been easy to provide a template for the repeater from the outside.
The $host keyword can only be used in the context of projection. Using it in any other context is not supported and will throw errors with high probability.
It is possible to provide multiple projections to a single slot.
<au-slot name="s1">s1</au-slot>
<au-slot name="s2">s2</au-slot><my-element>
<div au-slot="s2">p20</div>
<div au-slot="s1">p11</div>
<div au-slot="s2">p21</div>
<div au-slot="s1">p12</div>
</my-element>
<!-- Rendered (simplified): -->
<!--
<my-element>
<div>p11</div>
<div>p12</div>
<div>p20</div>
<div>p21</div>
</my-element>
-->This is useful for many cases. One evident example would a 'tabs' custom element.
<au-slot name="header"></au-slot>
<au-slot name="content"></au-slot><my-tabs>
<h3 au-slot="header">Tab1</h3>
<div au-slot="content">Tab1 content</div>
<h3 au-slot="header">Tab2</h3>
<div au-slot="content">Tab2 content</div>
<!--...-->
</my-tabs>This helps keep things closer that belong together. For example, keeping the tab-header and tab-content next to each other provides better readability and understanding of the code to the developer. On other hand, it still places the projected contents in the right slot.
Having more than one <au-slot> with the same name is also supported. This lets us project the same content to multiple slots declaratively, as can be seen in the following example.
<let details-shown.bind="false"></let>
<au-slot name="name"></au-slot>
<button click.delegate="detailsShown=!detailsShown">Toggle details</button>
<div if.bind="detailsShown">
<au-slot name="name"></au-slot>
<au-slot name="role"></au-slot>
<au-slot name="details"></au-slot>
</div><person-card>
<span au-slot="name"> John Doe </span>
<span au-slot="role"> Role1 </span>
<span au-slot="details"> Lorem ipsum </span>
</person-card>Note that projection for the name is provided once, but it gets duplicated in 2 slots. You can also see this example in action here.
<au-slot> changeSimilar like the standard <slot> element allows the ability to listen to changes in the content projected, <au-slot> also provides the capability to listen & react to changes.
@slotted decoratorOne way to subscribe to au-slot changes is via the @slotted decorator, like the following example:
<my-summary>
<p>This is a demo of the @slotted decorator</p>
<p>It can get all the "p" elements with a simple decorator</p>
</my-summary><p>Heading text</p>
<div>
<au-slot></au-slot>
</div>import { slotted } from 'aurelia';
export class MySummaryElement {
@slotted('p') paragraphs // assert paragraphs.length === 2
}After rendering, the MySummaryElement instance will have paragraphs value as an array of 2 <p> element as seen in the app.html.
The @slotted decorator will invoke change handler upon initial rendering, and whenever there's a mutation after wards, while the owning custom element is still active. By default, the callback will be selected based on the name of the decorated property. For example: paragraphs -> paragraphsChanged, like the following example:
import { slotted } from 'aurelia';
export class MySummaryElement {
@slotted('p') paragraphs // assert paragraphs.length === 2
paragraphsChanged(ps: HTMLParagraphElement[]) {
// do things
}
}<p>Heading text</p>
<div>
<au-slot></au-slot>
</div><my-summary>
<p>This is a demo of the @slotted decorator</p>
<p>It can get all the "p" elements with a simple decorator</p>
</my-summary>### Change handler callback reminders - The change handler will be called upon the initial rendering, and after every mutation afterwards while the custom element is still active {% %}
@slotted usageThe @slotted decorator can be used in multiple forms:
@slotted() prop
Use default options, observe projection on the default slot, and select all elements
@slotted('div') prop
Observe projection on the default slot, and select only div elements
@slotted('div', 'footer') prop
Observe projection on the footer slot and select only div elements
@slotted('*')
Observe projection on the default slot, and select all nodes, including text
@slotted('div', '*')
Observe projection on all slots, and select only div elements
@slotted({ query: 'div' })
Observe projection on the default slot, and select only div elements
@slotted({ slotName: 'footer' })
Observe projection on footer slot, and select all elements
@slotted({ callback: 'nodeChanged' })
Observe projection on default slot, and select all elements, and call nodeChanged method on projection change
Note: the `@slotted` decorator won't be notified if the children of a slotted node change — only if you change (e.g. add or delete) the actual nodes themselves. {% %}
slotchange bindingThe standard <slot> element dispatches slotchange events for application to react to changes in the projection. This behavior is also supported with <au-slot>. The different are with <slot>, it's an event while for <au-slot>, it's a callback as there's no host to dispatch an event, for <au-slot> is a containerless element.
The callback will be passed 2 parameters:
name
string
the name of the slot calling the change callback
nodes
Node[]
the list of the latest nodes that belongs to the slot calling the change callback
An example of using slotchange behavior may look like the following:
<my-summary>
<p>This is a demo of the @slotted decorator</p>
<p if.bind="describeMore">It can get all the "p" elements with a simple decorator</p>
</my-summary><p>Heading text</p>
<div>
<au-slot slotchange.bind="onContentChange"></au-slot>
<au-slot slotchange.bind="(name, nodes) => doSomething(name, nodes)"></au-slot>
</div>import { slotted } from 'aurelia';
export class MySummaryElement {
@slotted('p') paragraphs // assert paragraphs.length === 1
onContentChange = (name: string, nodes: Node[]) => {
// handle the new set of nodes here
console.assert(this === undefined);
}
doSomething(name: string, nodes: Node[]) {
console.assert(this instanceof MySummaryElement);
}
}slotchange callback remindersThe callback will not be called upon the initial rendering, it's only called when there's a mutation after the initial rendering.
The callback pass to slotchange of <au-slot> will be call with an undefined this, so you should either give it a lambda expression, or a function like the example above.
The nodes passed to the 2nd parameter of the slotchange callback will always be the latest list of nodes.
the slotchange callback doesn't fire if the children of a slotted node change — only if you change (e.g. add or delete) the actual nodes themselves.
Encountered an error and looking for answers? You've come to the right place.
This section is a work in progress and not yet complete. If you would like to help us document errors in Aurelia, we welcome all contributions.
Coded error in Aurelia comes with format: AURxxxx:yyyy where:
AUR is the prefix to indicate it's an error from Aurelia
xxxx is the code
: is the delimiter between the prefix, code and the dynamic information associated with the error
yyyy is the extra information, or parameters related to the error
The section below will list errors by their prefix, and code and give a corresponding explanation, and a way to fix them.
Dependency Injection errors can be found here.
AUR0701
This happens when a template has a single template element in your template, and it has as-local-element attribute on it
AUR0702
This happens when a template has one or more attributes that are supposed to be unique on its surrogate elements
AUR0703
This happens when a template controller attribute is used on a surrogate element of a template
AUR0704
This happens when an attribute on a <let/> element is used without .bind or .to-view command
AUR0705
This happens when enhancing a template with one or more element in it already have a class au on it
AUR0706
This happens when [au-slot] attribute is used on an element that is not an immediate child of a custom element
AUR0707
This happens when the template compiler encounters binding to a non-bindable property of a custom attribute
AUR0708
This happens when the template of a custom element has nothing beside template elements with as-local-element
AUR0709
This happens when an as-local-element template is not defined as an immediate child of the root of a custom element template
AUR0710
This happens when an as-local-element template has a <bindable> element inside its template, that is not not an immediate child of its fragment
AUR0711
This happens when a <bindable> inside an as-local-element template does not have a valid property attribute on it
AUR0712
This happens when an as-local-element template has 2 or more <bindable> elements with non-unique attribute or property attributes
AUR0713
This happens when an unknown binding command is encountered in a custom element template
AUR0714
This happens when a custom element or attribute definition has more than 1 primary bindable property
AUR0715
This happens when an as-local-template template has the value of as-local-template as an empty string
AUR0716
This happens when a custom element has 2 or more local elements with the same name
AUR0750
This happens when there is a binding that looks like this view.ref="...". This likely comes from a v1 template migration.
AUR0751
This happens when there is a ref binding in the template that does not have matching target. Most likely a custom attribute reference
AUR0752
This happens when a controller renders a custom element instruction that it doesn't have a registration. Normally happens in hand-crafted definition
AUR0753
This happens when a controller renders a custom attribute instruction that it doesn't have a registration. Normally happens in hand-crafted definition
AUR0754
This happens when a controller renders a template controller instruction that it doesn't have a registration. Normally happens in hand-crafted definition
AUR0755
This happens when a view factory provider tries to resolve but does not have a view factory associated
AUR0756
This happens when a view factory provider tries to resolve but the view factory associated does not have a valid name
AUR0757
This happens when IRendering.render is called with different number of targets and instructions
AUR0758
This happens when BindingCommand.getDefinition is called on a class/object without any binding command metadata associated
AUR0759
This happens when CustomAttribute.getDefinition is called on a class/object without any custom attribute metadata associated
AUR0760
This happens when CustomElement.getDefinition is called on a class/object without any custom element metadata associated
AUR0761
This happens when CustomElementDefinition.create is called with a string as first parameter
AUR0762
This happens when CustomElement.for is called on an element that does not have any custom element with a given name, without searching in ancestor elements
AUR0763
This happens when CustomElement.for is called and Aurelia isn't able to find any custom element with the given name in the given element, or its ancestors
AUR0764
This happens when CustomElement.for is called on an element with a given name, and Aurelia is unable to find any custom element in the given the element, or its ancestors
AUR0765
This happens when CustomElement.for is called on an element without a given name, and Aurelia is unable to find any custom element in the given element, or its ancestors
AUR0766
This happens when @processContent is called with a string as its first parameter, and Aurelia couldn't find the method on the decorated class
AUR0767
This happens when root property on an Aurelia instance is access before at least one application has been started with this Aurelia instance
AUR0768
This happens when a new Aurelia is created with a predefined container that already has IAurelia registration in it, or its ancestors
AUR0769
This happens when an Aurelia application is started with a document fragment before it's adopted by a document
AUR0770
This happens when Aurelia.prototype.start is called with a null/undefined value as the first parameter
AUR0771
This happens when Aurelia.prototype.dispose is called before the instance is stopped
AUR0772
This happens when the @watch decorator is used without a valid first parameter
AUR0773
This happens when the @watch decorator is used and Aurelia is not able to resolve the first parameter to a function
AUR0774
This happens when the @watch decorator is used on a class property instead of a method
AUR0651
This happens when the binding created .attr binding command is forced into two way mode against any attribute other than class/style
AUR0652
This happens when the default NodeObserverLocator.getObserver is called with an object and property combo that it doesn't know how to observe, and dirty checking is disabled
AUR0653
This happens when NodeObserverLocator property->observation events mapping is getting overridden
AUR0654
This happens when a <select> element is specified multiple, but the binding value is not an array
AUR0500
This happens when Controller.getCachedOrThrow throws
AUR0501
This happens when a custom element is specified containerless and has <slot> element in its template
AUR0502
This happens when a disposed controller is being activated
AUR0503
This happens when the internal state of a controller is corrputed during activation
AUR0504
This happens when a synthetic view is activated without a proper scope
AUR0505
This happens when the internal state of a controller is coruppted during deactivation
AUR0506
This happens when Aurelia fails to resolve a function from the first parameter of a @watch decorator
AUR0801
This happens when & self binding behavior is used on non-event binding
AUR0802
This happens when & updateTrigger binding behavior is used without any arguments
AUR0803
This happens when & updateTrigger binding behavior is used on binding without view -> view model observation
AUR0804
This happens when & updateTrigger binding behavior is used on binding that does not target a DOM element
AUR0805
This happens when <au-compose> scopeBehavior property is assigned a value that is not either auto or scoped
AUR0806
This happens when <au-compose> component binding is used with a custom element with containerless = true
AUR0807
This happens when there's a corrupted internal state of <au-compose> and activation is called twice
AUR0808
This happens when there's a corrupted internal state of <au-compose> and deactivation is called twice
AUR0809
This happens when <au-render> component binding is given a string value, and there's no custom element with matching name
AUR0810
This happens when else attribute does not follow an if attribute
AUR0811
This happens when portal attribute is a given an empty string as CSS selector fortarget, and strict mode is on
AUR0812
This happens when portal attribute couldn't find the target element to portal to, and strict mode is on
AUR0813
This happens when then/catch/pending attributes is used outside of a promise attribute
AUR0814
This happens when the internal of the repeat attribute get into a race condition and is corrupted
AUR0815
This happens when case/default-case attributes is used outside of a switch attribute
AUR0816
This happens when there are multiple default-case attributes inside a switch attribute
AUR0817
This happens when & signal binding behavior is used on binding that does not have handleChange method
AUR0818
This happens when & signal binding behavior is used without a valid name (non empty)
AUR0901
Dialog
This happens when an application is closed with some dialogs still open
AUR0903
Dialog
This happens when IDialogService.open is called without both component and template property
AUR0904
Dialog
This happens when the default configuration of the dialog plugin is used, as there's no registration associated for key interfaces
AUR0101
This happens when Aurelia couldn't find a binding behavior specified in an expression
AUR0102
This happens when there are two binding behaviors with the same name in an expression
AUR0103
This happens when a value converter for a given name couldn't be found during the evaluation of an expression
AUR0104
This happens when a value converter for a given name couldn't be found during the assignment of an expression
AUR0105
This happens when the special $host contextual property is accessed but no thing is found in the scope tree
AUR0106
This happens when an expression looks like this $host = ..., as $host is a readonly property
AUR0107
This happens when a call expression is evaluated but the object evaluated by the expression isn't a function
AUR0108
This happens when a binary expression is evaluated with an unknown operator
AUR0109
This happens when an unary expression is evaluated with an unknown operator
AUR0110
This happens when a tagged template (function call) is but the function specified isn't a function
AUR0111
This happens when a function call AST is evaluated but no function is found
AUR0112
This happens when a non-object or non-array value is assigned for destructured declaration for a repeat.for statement
AUR0151
An expression has an invalid character at the start
AUR0152
An expression has .. or ...
AUR0153
The parser encounters an unexpected identifier in an expression
AUR0154
The parser encounters an invalid AccessMember expression
AUR0155
The parers encounters an unexpected end in an expression
AUR0156
The parser encounters an unconsumable token in an expression
AUR0158
The expression has an invalid assignment
AUR0159
An expression has no valid identifier after the value converter ` | ` symbol
AUR0160
An expression has no valid identifier after the binding behavior & symbol
AUR0161
The parser encounters an invalid of keyword
AUR0162
The parser encounters an unconsumed token
AUR0163
The parser encounters an invalid binding identifier at left hand side of an of keyword
AUR0164
The parser encounters a literal object with a property declaration that it doesn't understand
AUR0165
An expression has an opening string quote ' or ", but no matching ending quote
AUR0166
An expression has an opening template string quote ```, but has no matching end
AUR0167
The parser encounters an unexpected token
AUR0168
The parser encounters an unexpected character
AUR0169
The parser encounters an unexpected character while parsing destructuring assignment expression
AUR0201
BindingBehavior.getDefinition is called on a class/object without any binding behavior metadata associated
AUR0202
ValueConverter.getDefinition is called on a class/object without any value converter metadata associated
AUR0203
BindingContext.get is called with null/undefined as the first parameter
AUR0204
Scope.fromOverride is called with null/undefined as the first parameter
AUR0205
Scope.fromParent is called with null/undefined as the first parameter
AUR0206
ConnectableSwitcher.enter is called with null/undefined as the first parameter
AUR0207
ConnectableSwitcher.enter is called with the currently active connectable
AUR0208
ConnectableSwitcher.exit is called with null/undefined as the first parameter
AUR0209
ConnectableSwitcher.exit is called with an inactive connectable
AUR0210
getCollectionObserver is called with an not-supported collection type
AUR0211
a binding subscried to an observer, but does not implement method handleChange
AUR0212
a binding subscribed to a collection observer, but does not implement method handleCollectionChange
AUR0220
a Set/Map size observer .setValue method is called
AUR0221
the setValue method on a computed property without a setter
AUR0222
Aurelia doesn't know how to observe a property on an object, and dirty checking is disabled
AUR0224
Encounters an invalid usage of @observable
AUR0225
An effect is attempted to run again, after it has stopped
AUR0226
An effect has reach its limit of recursive update
Router-Lite logs various events. Majority of those events are traces. The non-warn, non-error events are not logged in non-dev build, and are only available for troubleshooting in the dev-build. This section only lists the error codes.
AUR3155
The route context cannot be resolved from the given DOM node. This happens if the given node is not a custom element or not a child-node of a custom element.
AUR3166
This happens when an attempt to eagerly (without involving the route recognizer) recognize a routing instruction failed. If you are getting this error, please report it.
AUR3167
This happens when the application root is not yet set, but the router is trying to set a routing root. If you are getting this error, please report it.
AUR3168
This happens when a route context already exist for the application root; for example if it attempted to set the routing root more than once.
AUR3169
This happens when no controller exists for the application root. If you are getting this error, please report it.
AUR3170
A route context cannot be resolved for the given input.
AUR3171
This happens when the route node of the route context is not set. If you are getting this error, please report it.
AUR3172
This happens when the viewport agent of the route context is not set. If you are getting this error, please report it.
AUR3173
This happens the import() function is used as component, while configuring a route, but no path has been specified. This is not supported.
AUR3174
No viewport agent can be resolved for a given request.
AUR3175
This happens the import() function is used as component, while configuring a route, but the module does not export any aurelia custom element.
AUR3270
A routing transition failed.
AUR3271
The routing context of the router is not set. If you are getting this error, please report it.
AUR3350
Activation of component from a viewport failed due to incorrect state. If you are getting this error, please report it.
AUR3351
Deactivation of component from a viewport failed due to incorrect state. If you are getting this error, please report it.
AUR3352
The state of the viewport agent is not as expected. If you are getting this error, please report it.
AUR3353
The transition was either erred or cancelled via one of the can* hooks, but the router attempts to continue with the current instruction instead of cancelling it. If you are getting this error, please report it.
AUR3400
A navigation instruction cannot be created.
AUR3401
Neither the given routing instruction can be recognized, nor a fallback is configured.
AUR3401
The redirect route cannot be recognized.
AUR3403
toUrlComponent is invoked on a navigation instruction with incompatible type. This happens when the type of the instruction is a promise or a view-model.
AUR3450
Thrown by the navigation model when the endpoint for a path is not found.
AUR3500
Thrown by the route expression parser upon encountering an unexpected segment.
AUR3501
Thrown by the route expression parser when all of the given input string cannot be consumed.
AUR3502
Thrown if an unexpected segment is encountered during migrating parameters for redirect route.
AUR3550
Thrown when a re-attempt is made to call the getRouteConfig hook for the same component. If you are getting this error, please report it.
AUR3551
A custom element definition could not be resolved from the given string name, as no route context was provided. If you are getting this error, please report it.
AUR3552
A custom element definition could not be resolved from the given string name, as it is potentially not a custom element.
AUR3553
A custom element definition could not be resolved from theimport() function, as no route context was provided to resolve it.
AUR3554
The validation of a route config failed due to unexpected type of property.
AUR3555
The validation of a route config failed, as the config is either undefined or null.
AUR3556
The validation of a route config failed due to unexpected property.
AUR3556
The validation of a redirect route config failed due to unexpected property.
Learn to navigate from one view to another using the Router-Lite. Also learn about routing context.
This section details the various ways that you can use to navigate from one part of your application to another part. For performing navigation the router-lite offers couple of alternatives, namely the href and the load custom attributes, and the IRouter#load method.
href custom attributeYou can use the href custom attribute with an a (anchor) tag, with a string value. When the users click this link, the router-lite performs the navigation. This can be seen in action in the live example below.
The example shows that there are two configured routes, home and about, and in markup there are two anchor tags that points to these routes. Clicking those links the users can navigate to the desired components, as it is expected.
You can also use the parameterized routes with the href attribute, exactly the same way. To this end, you need to put the parameter value in the path itself and use the parameterized path in the href attribute. This is shown in the example below.
The example shows two configured routes; one with an optional parameter. The markup has three anchor tags as follows:
The last href attribute is an example of a parameterized route.
While configuring routes, an can be set explicitly. This id can also be used with the href attribute. This is shown in the example below.
Note that the example set a route id that is different than the defined path. These route-ids are later used in the markup as the values for the href attributes.
Note that using the route-id of a parameterized route with the href attribute might be limiting or in some cases non-operational as with href attribute there is no way to specify the parameters for the route separately. This case is handled by the .
You can target and/or viewports. To this end, you can use the following syntax.
The following live example, demonstrates that.
The example shows the following variations.
Note that using the viewport name in the routing instruction is optional and when omitted, the router uses the first available viewport.
The navigation using href attribute always happens in the current routing context; that is, the routing instruction will be successful if and only the route is configured in the current routing parent. This is shown in the example below.
In the example, the root component has two child-routes (c1, c2) and every child component in turn has 2 child-routes (gc11, and gc12 and gc21, and gc22 respectively) of their own. In this case, any href pointing to any of the immediate child-routes (and thus configured in the current routing parent) works as expected. However, when an href, like below (refer child1.ts), is used to navigate from one child component to another child component, it does not work.
In such cases, the router-lite offers the following syntax to make such navigation possible.
That is, you can use ../ prefix to instruct the router to point to the parent routing context. The prefix can also be used multiple times to point to any ancestor routing context. Naturally, this does not go beyond the root routing context.
Contextually, note that the also demonstrates the behavior of navigating in the current context. In that example, the root component uses r1, and r2 as route identifiers, which are the same identifiers used in the children to identify their respective child-routes. The route-ids are used in the markup with the href attributes. Despite being the same route-ids, the navigation works because unless specified otherwise, the routing instructions are constructed under the current routing context.
href custom attributeBy default the router-lite enables usage of the href custom attribute, as that ensures that the router-lite handles the routing instructions by default. There might be cases, where you want to avoid that. If you want to globally deactivate the usage of href, then you can customize the router configuration by setting false to the .
To disable/bypass the default handling of router-lite for any particular href attribute, you can avail couple of different ways as per your need and convenience.
Using external or data-external attribute on the a tag.
Using a non-null value for the target, other than the current window name, or _self.
Other than that, when clicking the link if either of the alt, ctrl, shift, meta key is pressed, the router-lite ignores the routing instruction and the default handling of clicking a link takes place.
Following example demonstrate these options.
load custom attributeAlthough the usage of href is the most natural choice, it has some limitations. Firstly, it allows navigating in the . However, a bigger limitation might be that the href allows usage of only string values. This might be bit sub-optimal when the routes have parameters, as in that case you need to know the order of the parameterized and static segments etc. to correctly compose the string path. In case the order of those segments are changed, it may cause undesired or unexpected results if your application.
To support structured way to constructing URL the router-lite offers another alternative namely the load attribute. This custom attribute accepts structured routing instructions as well as string-instructions, just like the href attribute. Before starting the discussion on the features supported exclusively by the load attribute, let us quickly review the following example of using string-instructions with the load attribute.
The example shows various instances of load attribute with various string instructions.
The following sections discuss the various other ways routing instruction can be used with the load attribute.
paramsUsing the bindable params property in the load custom attribute, you can bind the parameters for a parameterized route. The complete URL is then constructed from the given route and the parameters. Following is an example where the route-id is used with bound parameters.
The example above configures a route as follows. The route-id is then used in the markup with the bound params, as shown in the example below.
An important thing to note here is how the URL paths are constructed for each URL. Based on the given set of parameters, a path is selected from the configured set of paths for the route, that maximizes the number of matched parameters at the same time meeting the parameter constraints.
For example, the third instance (params: {p1: 4, p3: 5}) creates the path /c2/4/foo/?p3=5 (instance of 'c2/:p1/foo/:p2?' path) even though there is a path with :p3 configured. This happens because the bound parameters-object is missing the p2 required parameter in the path pattern 'c2/:p1/foo/:p2/bar/:p3'. Therefore, it constructs the path using the pattern 'c2/:p1/foo/:p2?' instead.
In other case, the fourth instance provides a value for p2 as well as a value for p3 that results in the construction of path /c2/6/foo/7/bar/8 (instance of 'c2/:p1/foo/:p2/bar/:p3'). This case also demonstrates the aspect of "maximization of parameter matching" while path construction.
One last point to note here is that when un-configured parameters are included in the params object, those are converted into query string.
routeThe bindable route property in the load attribute supports binding a class instead of route-id. The following example demonstrates using the classes (child1, child2) directly, instead of using the route-id.
You can see this in action below.
Just like the href attribute, the load attribute also supports navigating in the by default. The following example shows this where the root component has two child-routes with r1 and r2 route-ids and the child-components in turn defines their own child-routes using the same route-ids. The load attributes also use the route-ids as routing instruction. The routing works in this case, because the routes are searched in the same routing context.
However, this default behavior can be changed by binding the context property of the load custom attribute explicitly. To this end, you need to bind the instance of IRouteContext in which you want to perform the navigation. The most straightforward way to select a parent routing context is to use the parent property of the IRouteContext. The current IRouteContext can be injected using the @IRouteContext in the class constructor. Then one can use context.parent, context.parent?.parent etc. to select an ancestor context.
Such ancestor context can then be used to bind the context property of the load attribute as follows.
The following live example demonstrate this behavior.
Note that even though the ChildOne defines a route with r2 route-id, specifying the context explicitly, instructs the router-lite to look for a route with r2 route-id in the parent routing context.
Using the IRouteContext#parent path to select the root routing context is somewhat cumbersome when you intend to target the root routing context. For convenience, the router-lite supports binding null to the context property which instructs the router to perform the navigation in the root routing context.
This is shown in the following example.
When the route context selection involves only ancestor context, then the ../ prefix can be used when using string instruction. This also works when using the route-id. The following code snippets shows, how the previous example can be written using the ../ prefix.
active statusWhen using the load attribute, you can also leverage the bindable active property which is true whenever the associated route, bound to the href is active. In the following example, when a link in clicked and thereby the route is activated, the active* properties are bound from the views to true and thereby applying the .active-CSS-class on the a tags.
This can also be seen in the live example below.
The active bindable can be used for other purposes, other than adding CSS classes to the element. However, if that's what you need mostly the active property for, you may choose to configure the in the router configuration. When configured, the load custom attribute will add that configured class to the element when the associated routing instruction is active.
Along with the custom attributes on the markup-side, the router-lite also offers the IRouter#load method that can be used to perform navigation, with the complete capabilities of the JavaScript at your disposal. To this end, you have to first inject the router into your component. This can be done by using the IRouter decorator on your component constructor method as shown in the example below.
Now you are ready to use the load method, with many supported overloads at your disposal. These are outlined below.
The easiest way to use the load method is to use the paths directly.
With respect to that, this method supports the string instructions supported by the href and the load attribute. This is also shown in the example below.
There is a major important difference regarding the context selection in the IRouter#load method and the href and load custom attributes. By default, the custom attributes performs the navigation in the current routing context (refer the and documentation). However, the load method always use the root routing context to perform the navigation. This can be observed in the ChildOne and ChildTwo components where the load method is used the following way to navigate from ChildOne to ChildTwo and vice versa. As the load API uses the the root routing context by default, such routing instructions works. In comparison, note that with href we needed to use the .. prefix or with load method we needed to set the context to null.
However, on the other hand, you need to specify the routing context, when you want to navigate inside the current routing context. The most obvious use case is when you issue routing instruction for the child-routes inside a parent component. This can also be observed in ChildOne and ChildTwo components where a specific context is used as part of the to navigate to the child routes.
An array of paths (string) can be used to load components into sibling viewports. The paths can be parameterized or not non-parameterized.
This is shown in the example below.
The load method also support non-string routing instruction.
Using custom elements
You can use the custom element classes directly for which the routes have been configured. Multiple custom element classes can be used in an array to target sibling viewports.
This can be seen in action in the live example below.
Using custom element definitions
You can use the custom element definitions for which routes have been configured. Multiple definitions can be used in an array to target sibling viewports.
This can be seen in action in the live example below.
Using a function to return the view-model class
Similar to , for load you can use a function that returns a class as routing instruction. This looks like as follows.
This can be seen in action in the live example below.
Using import()
Similar to , for load you can use an import() statement to import a module. This looks like as follows.
This can be seen in action in the live example below.
Note that because invoking the import() function returns a promise, you can also use a promise directly with the load function.
Using a viewport instruction
Any kind of routing instruction used for the load method is converted to a viewport instruction tree. Therefore, you can also use a (partial) viewport instruction directly with the load method. This offers maximum flexibility in terms of configuration, such as routing parameters, viewports, children etc. Following are few examples, how the viewport instruction API can be used.
This can be seen in the example below.
Along with using the routing instructions, the load method allows you to specify different navigation options on a per-use basis. One of those, the context, you have already seen in the examples in the previous sections. This section describes other available options.
title
The title property allows you to modify the title as you navigate to your route. This looks like as follows.
Note that defining the title like this, overrides the title defined via the route configuration. This can also be seen in the action below where a random title is generated every time.
titleSeparator
As the name suggests, this provides a configuration option to customize the separator for the . By default router-lite uses | (pipe) as separator. For example if the root component defines a title 'Aurelia' and has a route /home with title Home, then the resulting title would be Home | Aurelia when navigating to the route /home. Using this option, you can customize the separator.
This can also be seen in the action below where a random title separator is selected every time.
queryParams
This option lets you specify an object to be serialized to a query string. This can be used as follows.
This can be seen in the live example below.
fragment
Like the queryParams, using the fragment option, you can specify the hash fragment for the new URL. This can be used as follows.
This can be seen in the live example below.
context
As by default, the load method performs the navigation relative to root context, when navigating to child routes, the context needs to be specified. This navigation option has also already been used in various examples previously. Various types of values can be used for the context.
The easiest is to use the custom element view model instance. If you are reading this documentation sequentially, then you already noticed this. An example looks like as follows.
Here is one of the previous example. Take a look at the child1.ts or child2.ts that demonstrates this.
You can also use an instance of IRouteContext directly. One way to grab the instance of IRouteContext is to get it inject via constructor using the @IRouteContext decorator. An example looks like as follows.
You can see this in action below.
Using a custom element controller instance is also supported to be used as a value for the context option. An example looks as follows.
You can see this in action below.
And lastly, you can use the HTML element as context. Following is live example of this.
historyStrategy
Using this navigation option, you can override the . Let us consider the example where three routes c1, c2, and c3 are configured with the push history strategy. Let us also assume that the following navigation instructions have already taken place.
After this, if we issue the following instruction,
then performing a history.back() should load the c1 route, as the state for c2 is replaced.
transitionPlan
Using this navigation option, you can override the per routing instruction basis. The following example demonstrates that even though the routes are configured with a specific transition plans, using the router API, the transition plans can be overridden.
This can be seen in action below.
For completeness it needs to be briefly discussed that apart from the explicit navigation instruction, there can be need to redirect the user to a different route or handle unknown routes gracefully. Other sections of the router-lite documentation discusses these topics in detail. Hence these topics aren't repeated here. Please refer to the linked documentations for more details.
Fallback using the
Fallback using the
<nav>
<a href="home">Home</a>
<a href="about">About</a>
</nav>import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
routes: [
{
path: ['', 'home'],
component: Home,
},
{
path: 'about',
component: About,
},
],
})
export class MyApp {}<nav>
<a href="home">Home</a>
<a href="about">About</a>
<a href="about/42">About/42</a>
</nav>import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
routes: [
{
path: ['', 'home'],
component: Home,
},
{
path: ['about/:id?'],
component: About,
},
],
})
export class MyApp {}import { route } from '@aurelia/router-lite';
import { ChildOne } from './child1';
import { ChildTwo } from './child2';
@route({
routes: [
{
id: 'r1',
path: ['', 'c1'],
component: ChildOne,
},
{
id: 'r2',
path: 'c2',
component: ChildTwo,
},
],
})
export class MyApp {}<nav>
<a href="r1">C1</a>
<a href="r2">C2</a>
</nav>import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({ name: 'gc-11', template: 'gc11' })
class GrandChildOneOne {}
@customElement({ name: 'gc-12', template: 'gc12' })
class GrandChildOneTwo {}
@route({
routes: [
{ id: 'r1', path: ['', 'gc11'], component: GrandChildOneOne },
{ id: 'r2', path: 'gc12', component: GrandChildOneTwo },
],
})
@customElement({
name: 'c-one',
template: `c1 <br>
<nav>
<a href="r1">gc11</a>
<a href="r2">gc12</a>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildOne {}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({ name: 'gc-21', template: 'gc21' })
class GrandChildTwoOne {}
@customElement({ name: 'gc-22', template: 'gc22' })
class GrandChildTwoTwo {}
@route({
routes: [
{ id: 'r1', path: ['', 'gc21'], component: GrandChildTwoOne },
{ id: 'r2', path: 'gc22', component: GrandChildTwoTwo },
],
})
@customElement({
name: 'c-two',
template: `c2 <br>
<nav>
<a href="r1">gc21</a>
<a href="r2">gc22</a>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildTwo {}{path1}[@{viewport-name}][+{path2}[@{sibling-viewport-name}]]<!-- Load the products' list in the first viewport and the details in the second viewport -->
<a href="products+details/${id}">Load products+details/${id}</a>
<!-- Load the details in the first viewport and the products' list in the second viewport -->
<a href="details/${id}+products">Load details/${id}+products</a>
<!-- Specifically target the named viewports -->
<a href="products@list+details/${id}@details">Load products@list+details/${id}@details</a>
<a href="products@details+details/${id}@list">Load products@details+details/${id}@list</a>
<!-- Load only the details in the specific named viewport -->
<a href="details/${id}@details">Load details/${id}@details</a>import { route } from '@aurelia/router-lite';
import { ChildOne } from './child1';
import { ChildTwo } from './child2';
import { NotFound } from './not-found';
@route({
routes: [
{
path: ['', 'c1'],
component: ChildOne,
},
{
path: 'c2',
component: ChildTwo,
},
{
path: 'not-found',
component: NotFound,
},
],
fallback: 'not-found',
})
@customElement({ name: 'my-app', template })
export class MyApp {}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({ name: 'gc-11', template: 'gc11' })
class GrandChildOneOne {}
@customElement({ name: 'gc-12', template: 'gc12' })
class GrandChildOneTwo {}
@route({
routes: [
{ id: 'gc11', path: ['', 'gc11'], component: GrandChildOneOne },
{ id: 'gc12', path: 'gc12', component: GrandChildOneTwo },
],
})
@customElement({
name: 'c-one',
template: `c1 <br>
<nav>
<a href="gc11">gc11</a>
<a href="gc12">gc12</a>
<a href="c2">c2 (doesn't work)</a>
<a href="../c2">../c2 (works)</a>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildOne {}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({ name: 'gc-21', template: 'gc21' })
class GrandChildTwoOne {}
@customElement({ name: 'gc-22', template: 'gc22' })
class GrandChildTwoTwo {}
@route({
routes: [
{ id: 'gc21', path: ['', 'gc21'], component: GrandChildTwoOne },
{ id: 'gc22', path: 'gc22', component: GrandChildTwoTwo },
],
})
@customElement({
name: 'c-two',
template: `c2 <br>
<nav>
<a href="gc21">gc21</a>
<a href="gc22">gc22</a>
<a href="c1">c1 (doesn't work)</a>
<a href="../c1">../c1 (works)</a>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildTwo {} <a href="c2">c2 (doesn't work)</a><a href="../c2">../c2 (works)</a><!-- my-app.html -->
<!-- instructions pointing to individual routes -->
<a load="c1">C1</a>
<a load="c2">C2</a>
<!-- instructions involving sibling viewports -->
<a load="c1+c2">C1+C2</a>
<a load="c1@vp2+c2@vp1">C1@vp2+C2@vp1</a>
<!-- child1 -->
<!-- instruction pointing to parent routing context -->
<a load="../c2">../c2</a>import { route } from '@aurelia/router-lite';
import { ChildTwo } from './child2';
@route({
routes: [
{
id: 'r2',
path: ['c2/:p1/foo/:p2?', 'c2/:p1/foo/:p2/bar/:p3'],
component: ChildTwo,
},
],
})
export class MyApp {}<!-- constructed path: /c2/1/foo/ -->
<a load="route: r2; params.bind: {p1: 1};">C2 {p1: 1}</a>
<!-- constructed path: /c2/2/foo/3 -->
<a load="route: r2; params.bind: {p1: 2, p2: 3};">C2 {p1: 2, p2: 3}</a>
<!-- constructed path: /c2/4/foo/?p3=5 -->
<a load="route: r2; params.bind: {p1: 4, p3: 5};">C2 {p1: 4, p3: 5}</a>
<!-- constructed path: /c2/6/foo/7/bar/8 -->
<a load="route: r2; params.bind: {p1: 6, p2: 7, p3: 8};">C2 {p1: 6, p2: 7, p3: 8}</a>
<!-- constructed path: /c2/9/foo/10/bar/11?p4=awesome&p5=possum -->
<a load="route: r2; params.bind: {p1: 9, p2: 10, p3: 11, p4: 'awesome', p5: 'possum'};">C2 {p1: 9, p2: 10, p3: 11, p4: 'awesome', p5: 'possum'}</a>// my-app.ts
import { ChildOne } from './child1';
import { ChildTwo } from './child2';
export class MyApp {
private readonly child1: typeof ChildOne = ChildOne;
private readonly child2: typeof ChildTwo = ChildTwo;
}<!-- my-app.html -->
<a load="route.bind: child1">C1</a>
<a load="route.bind: child2; params.bind: {p1: 1};">C2 {p1: 1}</a>
<a load="route.bind: child2; params.bind: {p1: 2, p2: 3};">C2 {p1: 2, p2: 3}</a>
<a load="route.bind: child2; params.bind: {p1: 4, p3: 5};">C2 {p1: 4, p3: 5}</a>
<a load="route.bind: child2; params.bind: {p1: 6, p2: 7, p3: 8};">C2 {p1: 6, p2: 7, p3: 8}</a>
<a load="route.bind: child2; params.bind: {p1: 9, p2: 10, p3: 11, p4: 'awesome', p5: 'possum'};">C2 {p1: 9, p2: 10, p3: 11, p4: 'awesome', p5: 'possum'}</a>export class ChildOne {
private readonly parentCtx: IRouteContext;
public constructor(@IRouteContext ctx: IRouteContext) {
this.parentCtx = ctx.parent;
}
}<a load="route: r2; context.bind: parentCtx">c2</a><a load="route: r2; context.bind: null">Go to root c2</a><a load="route: ../r2">c2</a><style>
a.active {
font-weight: bolder;
}
</style>
<nav>
<a
load="route:foo; params.bind:{id: 1}; active.bind:active1"
active.class="active1"
>foo/1</a
>
<a load="route:foo/2; active.bind:active2" active.class="active2">foo/2</a>
</nav>
<au-viewport></au-viewport>import { IRouter, IRouteableComponent } from '@aurelia/router-lite';
export class MyComponent {
public constructor(@IRouter private readonly router: IRouter) { }
}router.load('c1')
router.load('c2')
router.load('c2/42')
router.load('c1+c2')
router.load('c1@vp2+c2@vp1')// in ChildOne
router.load('c2');
// in ChildTwo
router.load('c1');// in ChildOne
router.load('gc11', { context: this });
// in ChildTwo
router.load('gc21', { context: this });router.load(['c1', 'c2']);
router.load(['c1', 'c2/21']);router.load(ChildOne);
router.load([ChildOne, ChildTwo]);
router.load(GrandChildOneOne, { context: this });import { CustomElement } from '@aurelia/runtime-html';
router.load(CustomElement.getDefinition(ChildOne));
router.load([
CustomElement.getDefinition(ChildOne),
CustomElement.getDefinition(ChildTwo)
]);
router.load(
CustomElement.getDefinition(GrandChildOneOne),
{ context: this }
);router.load(() => ChildOne);
router.load([() => ChildOne, () => ChildTwo]);
router.load(() => GrandChildOneOne, { context: this });router.load(import('./child1')); // uses the default or first non-default import
router.load([
import('./child1'),
import('./child2').then(m => m.Child2) // selective import
]);router.load(Promise.resolve({ ChildOne }));// using a route-id
router.load({ component: 'c1' });
// using a class
router.load({ component: ChildTwo });
// load sibling routes
router.load([
// use custom element definition
{ component: CustomElement.getDefinition(ChildOne) },
// use a function returning class
{ component: () => ChildTwo, params: { id: 42 } },
]);
// load sibling routes with nested children and parameters etc.
router.load([
// using path
{
component: 'c1',
children: [{ component: GrandChildOneTwo }],
viewport: 'vp2',
},
// using import
{
component: import('./child2'),
params: { id: 21 },
children: [{ component: GrandChildTwoTwo }],
viewport: 'vp1',
},
]);router.load(Home, { title: 'Some title' });router.load(Home, { titleSeparator: '-' });// the generated URL: /home?foo=bar&fizz=buzz
router.load(
'home',
{
queryParams: {
foo: 'bar',
fizz: 'buzz',
}
}
);// the generated URL: /home#foobar
router.load(
'home',
{
fragment: 'foobar'
}
);router.load('child-route', { context: this });import { IRouteContext, IRouter, Params, route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@customElement({ name: 'gc-21', template: 'gc21' })
class GrandChildTwoOne {}
@customElement({ name: 'gc-22', template: 'gc22' })
class GrandChildTwoTwo {}
@route({
routes: [
{ id: 'gc21', path: ['', 'gc21'], component: GrandChildTwoOne },
{ id: 'gc22', path: 'gc22', component: GrandChildTwoTwo },
],
})
@customElement({
name: 'c-two',
template: `c2 <br>
id: \${id}
<nav>
<button click.trigger="load('gc21', true)">Go to gc21</button>
<button click.trigger="load('gc22', true)">Go to gc22</button>
<button click.trigger="load('c1')" >Go to c1 </button>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildTwo {
private id: string;
public constructor(
@IRouter private readonly router: IRouter,
// injected instance of IRouteContext
@IRouteContext private readonly context: IRouteContext
) {}
private load(route: string, useCurrentContext: boolean = false) {
void this.router.load(
route,
useCurrentContext
? {
// use the injected IRouteContext as navigation context.
context: this.context
}
: undefined
);
}
public loading(params: Params) {
this.id = params.id ?? 'NA';
}
}import { IRouter, route } from '@aurelia/router-lite';
import {
customElement,
type ICustomElementController,
type IHydratedCustomElementViewModel,
} from '@aurelia/runtime-html';
@customElement({ name: 'gc-11', template: 'gc11' })
class GrandChildOneOne {}
@customElement({ name: 'gc-12', template: 'gc12' })
class GrandChildOneTwo {}
@route({
routes: [
{ id: 'gc11', path: ['', 'gc11'], component: GrandChildOneOne },
{ id: 'gc12', path: 'gc12', component: GrandChildOneTwo },
],
})
@customElement({
name: 'c-one',
template: `c1 <br>
<nav>
<button click.trigger="load('gc11', true)">Go to gc11</button>
<button click.trigger="load('gc12', true)">Go to gc12</button>
<button click.trigger="load('c2')" >Go to c2 </button>
</nav>
<br>
<au-viewport></au-viewport>`,
})
export class ChildOne implements IHydratedCustomElementViewModel {
// set by aurelia pipeline
public readonly $controller: ICustomElementController<this>;
public constructor(@IRouter private readonly router: IRouter) {}
private load(route: string, useCurrentContext: boolean = false) {
void this.router.load(
route,
useCurrentContext
? {
// use the custom element controller as navigation context
context: this.$controller
}
: undefined
);
}
}router.load('c1');
router.load('c2');router.load('c3', { historyStrategy: 'replace' })@route({
transitionPlan: 'replace',
routes: [
{
id: 'ce1',
path: ['ce1/:id'],
component: CeOne,
transitionPlan: 'invoke-lifecycles',
},
{
id: 'ce2',
path: ['ce2/:id'],
component: CeTwo,
transitionPlan: 'replace',
},
],
})
@customElement({
name: 'my-app',
template: `
<button click.trigger="navigate('ce1/42')">ce1/42 (default: invoke lifecycles)</button><br>
<button click.trigger="navigate('ce1/43')">ce1/43 (default: invoke lifecycles)</button><br>
<button click.trigger="navigate('ce1/44', 'replace')">ce1/44 (override: replace)</button><br>
<br>
<button click.trigger="navigate('ce2/42')">ce2/42 (default: replace)</button><br>
<button click.trigger="navigate('ce2/43')">ce2/43 (default: replace)</button><br>
<button click.trigger="navigate('ce2/44', 'invoke-lifecycles')">ce2/44 (override: invoke lifecycles)</button><br>
<au-viewport></au-viewport>
`,
})
export class MyApp {
public constructor(@IRouter private readonly router: IRouter) {}
private navigate(
path: string,
transitionPlan?: 'replace' | 'invoke-lifecycles'
) {
void this.router.load(
path,
transitionPlan ? { transitionPlan } : undefined
);
}
}Learn about configuring routes in Router-Lite.
The router takes your routing instructions and matches the URL to one of the configured Routes to determine which components to render. To register routes you can either use the @route decorator or you can use the static routes property to register one or more routes in your application. This section describes the route configuration options in details.
The routing configuration syntax for router-lite is similar to that of other routers you might have worked with before. If you have worked with Express.js routing, then the syntax will be very familiar to you.
A route is an object containing a few required properties that tell the router what component to render, what URL it should match on and other route-specific configuration options.
The most usual case of defining a route configuration is by specifying the path and the component properties. The idea is to use the path property to define a pattern, which when seen in the URL path, the view model defined using the component property is activated by the router-lite. Simply put, a routing configuration is a mapping between one or more path patterns to components. Below is the simple example (from the getting started section) of this.
import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
title: 'Aurelia',
routes: [
{
path: ['', 'home'],
component: Home,
},
{
path: 'about',
component: About,
},
],
})
export class MyApp {}For the example above, when the router-lite sees either the path / or /home, it loads the Home component and if it sees the /about path it loads the About component.
Note that the example above uses the @route decorator. In case you cannot use the decorator, you can use the static properties instead. The example shown above can be rewritten as follows.
import { Routeable } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
export class MyApp {
// corresponds to the `title` property in the options object used in the @route decorator.
static title: string = 'Aurelia';
// corresponds to the `routes` property in the options object used in the @route decorator.
static routes: Routeable[] = [
{
path: ['', 'home'],
component: Home,
},
{
path: 'about',
component: About,
},
];
}As the re-written example shows, you can convert the properties in the options object used for the @route decorator into static properties in the view model class.
Apart from the static API including the @route decorator, there is also an instance-level hook named getRouteConfig that you can use to configure your routes. This is shown in the example below.
import { IRouteConfig, RouteNode } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
export class MyApp {
public getRouteConfig(_parentConfig: IRouteConfig | null, _routeNode: RouteNode | null): IRouteConfig {
return {
routes: [
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: 'about',
component: About,
title: 'About',
},
],
};
}
}See this in action below.
Note that the hook is also supplied with a parent route configuration, and the new route node. These values can be nullable; for example, for root node there is no parent route configuration.
The getRouteConfig can also be async. This is shown in the example below.
import { IRouteConfig, RouteNode } from '@aurelia/router-lite';
export class MyApp {
public getRouteConfig(_parentConfig: IRouteConfig | null, _routeNode: RouteNode | null): IRouteConfig {
return {
routes: [
{
path: ['', 'home'],
component: await import('./home').then((x) => x.Home),
title: 'Home',
},
{
path: 'about',
component: await import('./about').then((x) => x.About),
title: 'About',
},
],
};
}
}See this in action below.
path and parametersThe path defines one or more patterns, which are used by the router-lite to evaluate whether or not an URL matches a route or not. A path can be either a static string (empty string is also allowed, and is considered as the default route) without any additional dynamic parts in it, or it can contain parameters. The paths defined on every routing hierarchy (note that routing configurations can be hierarchical) must be unique.
Required parameters are prefixed with a colon. The following example shows how to use a required parameter in the path.
import { route } from '@aurelia/router-lite';
import { Product } from './product';
@route({
routes: [
{
path: 'products/:id',
component: Product,
},
],
})
export class MyApp {}When a given URL matches one such route, the parameter value is made available in the canLoad, and load routing hooks.
import { IRouteViewModel, Params } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
import template from './product.html';
@customElement({ name: 'pro-duct', template })
export class Product implements IRouteViewModel {
public canLoad(params: Params): boolean {
console.log(params.id);
return true;
}
}Note that the value of the id parameter as defined in the route configuration (:id) is available via the params.id. Check out the live example to see this in action.
Optional parameters start with a colon and end with a question mark. The following example shows how to use an optional parameter in the path.
import { route } from '@aurelia/router-lite';
import { Product } from './product';
@route({
routes: [
{
path: 'product/:id?',
component: Product,
},
],
})
export class MyApp {}In the example, shown above, the Product component is loaded when the router-lite sees paths like /product or /product/some-id, that is irrespective of a value for the id parameter. You can see the live example below.
Note that there is an additional link added to the products.html to fetch a random product.
<li>
<a href="../product">Random product</a>
</li>As the id parameter is optional, even without a value for the id parameter, clicking the link loads the Product component. Depending on whether or not there is a value present for the id parameter, the Product component generates a random id and loads that.
public canLoad(params: Params): boolean {
let id = Number(params.id);
if (Number.isNaN(id)) {
id = Math.ceil(Math.random() * 30);
}
this.promise = this.productService.get(id);
return true;
}The wildcard parameters, start with an asterisk instead of a colon, act as a catch-all, capturing everything provided after it. The following example shows how to use a wildcard parameter in the path.
import { route } from '@aurelia/router-lite';
import { Product } from './product';
@route({
routes: [
{
id: 'foo',
path: ['product/:id', 'product/:id/*rest'],
component: Product,
},
],
})
export class MyApp {}In the example, shown above, the Product component is loaded when the router-lite sees paths like /product/some-id or /product/some-id/foo/bar. You can see the live example below.
The example utilizes a wildcard parameter named rest, and when the value of rest is 'image', an image for the product is shown. To this end, the canLoad hook of the Product view-model reads the rest parameter.
public canLoad(params: Params): boolean {
const id = Number(params.id);
this.promise = this.productService.get(id);
this.showImage = params.rest == 'image';
return true;
}You can configure the title for the routes while you are configuring the routes. The title can be configured in the root level, as well as in the individual route level. This can be seen in the following example using the @route decorator.
import { route, IRouteViewModel } from '@aurelia/router-lite';
@route({
title: 'Aurelia', // <-- this is the base title
routes: [
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
}
]
})
export class MyApp implements IRouteViewModel {}If you prefer using the static routes property, the title can be set using a static title property in the class. The following example has exactly the same effect as of the previous example.
import { IRouteViewModel, Routeable } from "aurelia";
export class MyApp implements IRouteViewModel {
static title: string = 'Aurelia'; // <-- this is the base title
static routes: Routeable[] = [
{
path: ['', 'home'],
component: import('./components/home-page'),
title: 'Home',
}
];
}With this configuration in place, the default-built title will be Home | Aurelia when user is navigated to / or /home route. That is, the titles of the child routes precedes the base title. You can customize this default behavior by using a custom buildTitle function when customizing the router configuration.
Note that, instead of a string, a function can also be used for title to lazily set the title.
By specifying the redirectTo property on our route, we can create route aliases. These allow us to redirect to other routes. In the following example, we redirect our default route to the home page and the about-us to about page.
@route({
routes: [
{ path: '', redirectTo: 'home' },
{ path: 'about-us', redirectTo: 'about' },
{
path: 'home',
component: Home,
},
{
path: 'about',
component: About,
},
],
})
export class MyApp {}You can see this action below.
Note that redirection also works when there are multiple paths/aliases defined for the same component.
@route({
routes: [
{ path: 'foo', redirectTo: 'home' },
{ path: 'bar', redirectTo: 'about' },
{ path: 'fizz', redirectTo: 'about-us' },
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: ['about', 'about-us'],
component: About,
},
],
})
export class MyApp {}You can see this action below.
You can use route parameters for redirectTo. The following example shows that the parameters from the about-us path is rearranged to the about path.
import { route } from '@aurelia/router-lite';
import { About } from './about';
@route({
routes: [
{ path: 'about-us/:foo/:bar', redirectTo: 'about/:bar/:foo' },
{
path: 'about/:p1?/:p2?',
component: About,
title: 'About',
},
],
})
export class MyApp {}You can see this action below.
We can instruct the router-lite to redirect the users to a different configured path, whenever it sees any unknown/un-configured paths. To this end, we can use the fallback configuration option. Following example shows how to use this configuration option.
As the example shows, the fallback is configured as follows.
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
import { Home } from './home';
import { About } from './about';
import { NotFound } from './not-found';
@route({
routes: [
{
path: ['', 'home'],
component: Home,
title: 'Home',
},
{
path: 'about',
component: About,
title: 'About',
},
{
path: 'notfound',
component: NotFound,
title: 'Not found',
},
],
fallback: 'notfound', // <-- fallback configuration
})
export class MyApp {}There is a custom element, named NotFound, which is meant to be loaded when any unknown/un-configured route is encountered. As you can see in the above example, clicking the "Foo" link that is with un-configured href, leads to the NotFound view.
Another way of defining the fallback is to use the route-id. The following example demonstrates this behavior, where the NotFound view can be reached via multiple aliases, and instead of choosing one of these aliases the route-id is used to refer the route.
The name of the custom element, meant to be displayed for any un-configured route can also be used to define fallback. The following example demonstrates this behavior, where not-found, the name of custom element NotFound, is used to refer the route.
An important point to note here is that when you are using the custom element name as fallback, you need to ensure that the custom element is registered to the DI container. Note that in the example above, the NotFound component is registered to the DI container in main.ts.
A fallback defined on parent is inherited by the children (to know more about hierarchical routing configuration, refer the documentation). However, every child can override the fallback as needed. The following example demonstrate this. The root has two sibling viewports and two children components can be loaded into each of those by clicking the link. Every child defines their own child routing configuration. The root defines a fallback and one of the children overrides the fallback by defining one of its' own. With this configuration in place, when navigation to a un-configured route ('Foo') is attempted for each children, one loads the overridden version whereas the other loads the fallback inherited from the parent (in this case the root).
A function can be used for fallback. The function takes the following signature.
fallback(viewportInstruction: ViewportInstruction, routeNode: RouteNode, context: IRouteContext): string;An example can look like below, where the example redirects the user to NF1 component if an attempt to load a path /foo is made. Every other attempt to load an unknown path is results loading the NF2 component.
import { customElement } from '@aurelia/runtime-html';
import {
IRouteContext,
ITypedNavigationInstruction_string,
route,
RouteNode,
ViewportInstruction,
} from '@aurelia/router-lite';
@customElement({ name: 'ce-a', template: 'a' })
class A {}
@customElement({ name: 'n-f-1', template: 'nf1' })
class NF1 {}
@customElement({ name: 'n-f-2', template: 'nf2' })
class NF2 {}
@route({
routes: [
{ id: 'r1', path: ['', 'a'], component: A },
{ id: 'r2', path: ['nf1'], component: NF1 },
{ id: 'r3', path: ['nf2'], component: NF2 },
],
fallback(vi: ViewportInstruction, _rn: RouteNode, _ctx: IRouteContext): string {
return (vi.component as ITypedNavigationInstruction_string).value === 'foo' ? 'r2' : 'r3';
},
})
@customElement({
name: 'my-app',
template: `
<nav>
<a href="a">A</a>
<a href="foo">Foo</a>
<a href="bar">Bar</a>
</nav>
<au-viewport></au-viewport>`
})
export class MyApp {}You can also see this in action below.
You can also use non-string fallbacks. For example, you can use a class as the value for fallback; such as fallback: NotFound. Or, if you are using a function, you choose to return a class instead of returning a string. These combinations are also supported by router-lite.
Routes can be marked as case-sensitive in the configuration, allowing the navigation to the component only when the case matches exactly the configured path. See the example below where the navigation to the "about" page is only successful when the casing matches.
import { route } from '@aurelia/router-lite';
import { About } from './about';
@route({
routes: [
{
path: 'AbOuT',
component: About,
caseSensitive: true,
},
],
})
export class MyApp {}Thus, only an attempt to the /AbOuT path loads the About component; any attempt with a different casing is navigated to the fallback. See this in action below.
There are few other routing configuration which aren't discussed above. Our assumption is that these options are more involved and might not be used that often. Moreover, to understand the utility of these options fully, knowledge of other parts of the route would be beneficial. Therefore, this section only briefly introduces these options providing links to the sections with detailed examples.
id — The unique ID for this route. The router-lite implicitly generates a id for a given route, if an explicit value for this property is missing. Although this is not really an advanced property, due to the fact that a route can be uniquely identified with id, it can be used in many interesting ways. For example, this can be used to generate the hrefs in the view when using the load custom attribute or using the Router#load API. Using this property is also very convenient when there are multiple aliases for a single route, and we need a unique way to refer to this route.
transitionPlan — How to behave when the currently active component is scheduled to be loaded again in the same viewport. For more details, please refer the documentation.
viewport — The name of the viewport this component should be loaded into. This demands a full fledged documentation of its own. Refer to the viewport documentation for more details.
data — Any custom data that should be accessible to matched components or hooks. The value of this configuration property must be an object and the object can take any shape (that is there is no pre-defined interface/class for this object). A typical use-case for the data property is to define the permissions, required by the users, when they attempt to navigate to this route. Refer an example of this.
nav - Set this flag to false (default value is true), to instruct the router not to add the route to the navigation model. This is typically useful to exclude routes from the public navigation menu.
Before finishing the section on the route configuration, we need to discuss one last topic for completeness, and that is how many different ways you can configure the component. Throughout various examples so far we have seen that components are configured by importing and using those in the routing configuration. However, there are many other ways in which the components can be configured. This section discusses those.
import()Components can be configured using the import() or dynamic import. Instead of statically importing the components, those can be imported using import()-syntax, as the example shows below.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
- import { About } from './about';
- import { Home } from './home';
@route({
routes: [
{
path: ['', 'home'],
- component: Home,
+ component: import('./home'),
title: 'Home',
},
{
path: 'about',
- component: About,
+ component: import('./about'),
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}You can see this in action below.
Components can be configured using only the custom-element name of the component.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
- import { About } from './about';
- import { Home } from './home';
@route({
routes: [
{
path: ['', 'home'],
- component: Home,
+ component: 'ho-me', // <-- assuming that Home component has the name 'ho-me'
title: 'Home',
},
{
path: 'about',
- component: About,
+ component: 'ab-out', // <-- assuming that About component has the name 'ab-out'
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}However, when configuring the route this way, you need to register the components to the DI.
// main.ts
import { RouterConfiguration } from '@aurelia/router-lite';
import { Aurelia, StandardConfiguration } from '@aurelia/runtime-html';
import { About } from './about';
import { Home } from './home';
import { MyApp as component } from './my-app';
(async function () {
const host = document.querySelector<HTMLElement>('app');
const au = new Aurelia();
au.register(
StandardConfiguration,
RouterConfiguration,
// component registrations
Home,
About,
);
au.app({ host, component });
await au.start();
})().catch(console.error);You can see this configuration in action below.
Components can be configured using a function that returns a class.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
- import { About } from './about';
- import { Home } from './home';
@route({
routes: [
{
path: ['', 'home'],
- component: Home,
+ component: () => {
+ @customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
+ class Home {
+ private readonly message: string = 'Welcome to Aurelia2 router-lite!';
+ }
+ return Home;
+ },
title: 'Home',
},
{
path: 'about',
- component: About,
+ component: () => {
+ @customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
+ class About {
+ private readonly message = 'Aurelia2 router-lite is simple';
+ }
+ return About;
+ },
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}You can see this configuration in action below.
Components can be configured using custom element definition.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
- import { About } from './about';
- import { Home } from './home';
+ class Home {
+ private readonly message: string = 'Welcome to Aurelia2 router-lite!';
+ }
+ const homeDefn = CustomElementDefinition.create(
+ { name: 'ho-me', template: '<h1>${message}</h1>' },
+ Home
+ );
+ CustomElement.define(homeDefn, Home);
+
+ class About {
+ private readonly message = 'Aurelia2 router-lite is simple';
+ }
+ const aboutDefn = CustomElementDefinition.create(
+ { name: 'ab-out', template: '<h1>${message}</h1>' },
+ About
+ );
+ CustomElement.define(aboutDefn, About);
@route({
routes: [
{
path: ['', 'home'],
- component: Home,
+ component: homeDefn,
title: 'Home',
},
{
path: 'about',
- component: About,
+ component: aboutDefn,
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}You can see this configuration in action below.
Components can be configured using custom element instance.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import template from './my-app.html';
- import { About } from './about';
- import { Home } from './home';
+ @customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
+ class Home {
+ private readonly message: string = 'Welcome to Aurelia2 router-lite!';
+ }
+
+ @customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
+ class About {
+ private readonly message = 'Aurelia2 router-lite is simple';
+ }
@route({
routes: [
{
path: ['', 'home'],
- component: Home,
+ component: new Home(),
title: 'Home',
},
{
path: 'about',
- component: About,
+ component: new About(),
title: 'About',
},
],
})
@customElement({ name: 'my-app', template })
export class MyApp {}You can see this configuration in action below.
Using router-lite it is also possible to use the routed view model classes directly as routes configuration. While doing so, if no paths have been explicitly configured for the components, the custom element name and aliases can be used as routing instructions. The following example demonstrates that the C1 and C2 classes are used directly as the child routes for the Root.
@customElement({ name: 'c-1', template: 'c1', aliases: ['c-a', 'c-one'] })
class C1 { }
@customElement({ name: 'c-2', template: 'c2', aliases: ['c-b', 'c-two'] })
class C2 { }
@route({
routes: [C1, C2]
})
@customElement({ name: 'ro-ot', template: '<au-viewport></au-viewport>' })
class Root { }The example above implies that router.load('c-1'), or router.load('c-a') and router.load('c-2'), router.load('c-two') will load the C1 and C2 respectively.
The examples discussed so far demonstrate the classic use-cases of route configurations where the parents define the child routes. Another aspect of these examples are that all the route configurations are centralized on the parent component. This section provides some examples where that configuration is distributed across different components.
We start by noting that every component can define its own path. This is shown in the following example.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
routes: [Home, About],
})
@customElement({
name: 'my-app',
template: `
<nav>
<a href="home">Home</a>
<a href="about">About</a>
</nav>
<au-viewport></au-viewport>
`
})
export class MyApp {}
import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route(['', 'home'])
@customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
export class Home {
private readonly message: string = 'Welcome to Aurelia2 router-lite!';
}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route('about')
@customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
export class About {
private readonly message = 'Aurelia2 router-lite is simple';
}The example shows that both Home and About uses the @route decorator to define their own paths. This reduces the child-route configuration for MyApp to @route({ routes: [Home, About] }). The example can be seen in action below.
Note that other properties of route configuration can also be used in this way.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
routes: [Home, About],
})
@customElement({
name: 'my-app',
template: `
<nav>
<a href="home">Home</a>
<a href="about">About</a>
</nav>
<au-viewport></au-viewport>
`
})
export class MyApp {}
import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: ['', 'home'], title: 'Home' })
@customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
export class Home {
private readonly message: string = 'Welcome to Aurelia2 router-lite!';
}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: 'about', title: 'About' })
@customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
export class About {
private readonly message = 'Aurelia2 router-lite is simple';
}The previous example demonstrates that the Home and About components define the title for themselves. The example can be seen in action below.
While adapting to distributes routing configuration, the parent can still override the configuration for its children. This makes sense, because even if a component defines its own path, title etc. the parent may choose to reach (route) the component via a different path or display a different title when the component is loaded. This is shown below, where the MyApp overrides the routing configurations defined by About.
import { customElement } from '@aurelia/runtime-html';
import { route } from '@aurelia/router-lite';
import { Home } from './home';
import { About } from './about';
@route({
routes: [
Home,
{ path: 'about-us', component: About, title: 'About us' }
],
})
@customElement({
name: 'my-app',
template: `
<nav>
<a href="home">Home</a>
<a href="about-us">About</a>
</nav>
<au-viewport></au-viewport>
`
})
export class MyApp {}
import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: ['', 'home'], title: 'Home' })
@customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
export class Home {
private readonly message: string = 'Welcome to Aurelia2 router-lite!';
}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: 'about', title: 'About' })
@customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
export class About {
private readonly message = 'Aurelia2 router-lite is simple';
}This can be seen in action below.
You can also use the @route decorator and the getRouteConfig together.
import { customElement } from '@aurelia/runtime-html';
import {
IRouteConfig,
IRouteViewModel,
route,
RouteNode,
} from '@aurelia/router-lite';
import template from './my-app.html';
import { Home } from './home';
import { About } from './about';
@route({ title: 'Aurelia2' })
@customElement({
name: 'my-app',
template: `
<nav>
<a href="home">Home</a>
<a href="about">About</a>
</nav>
<au-viewport></au-viewport>
`
})
export class MyApp implements IRouteViewModel {
public getRouteConfig?(
parentConfig: IRouteConfig | null,
routeNode: RouteNode | null
): IRouteConfig {
return {
routes: [Home, About],
};
}
}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: ['', 'home'], title: 'Home' })
@customElement({ name: 'ho-me', template: '<h1>${message}</h1>' })
export class Home {
private readonly message: string = 'Welcome to Aurelia2 router-lite!';
}import { route } from '@aurelia/router-lite';
import { customElement } from '@aurelia/runtime-html';
@route({ path: 'about', title: 'About' })
@customElement({ name: 'ab-out', template: '<h1>${message}</h1>' })
export class About {
private readonly message = 'Aurelia2 router-lite is simple';
}This can be seen in action below.
The advantage of this kind of distributed configuration is that the routing configuration of every component is defined by every component itself, thereby encouraging encapsulation, leaving the routing configuration at the parent level to merely listing out its child components. On the other hand, highly distributed route configuration may prevent easy overview of the configured routes. That's the trade-off. Feel free to mix and match as per your need and aesthetics.