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:
You 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:
This will build your application for production and create a new folder called dist
.
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 Hello World tutorial 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 Node.js website.
Aurelia does not require you to install any global Node packages, instead of using the Makes 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 here. And if you want to dive even deeper (perhaps you've dabbled in Aurelia before) we have a fantastic selection of tutorials here.
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!
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.
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.
Learn to use Aurelia's project scaffold tooling to create your first project setup.
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".
Get 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.
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.
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.
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:
Congratulations! You just ran your first Aurelia app. Now, let's get building.
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.
Your journey with Aurelia begins here in our meticulously crafted documentation. Start with the 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 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 "" 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 . It will show you how to create a project and build your first components using Aurelia's powerful templating system.
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:
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:
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.
Binding image attributes, such as src
and alt
, is as simple as:
Bind to the disabled
attribute to disable buttons and inputs dynamically:
Choose between innerhtml
for rendering HTML content and textcontent
for text-only content:
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:
Apply the attribute binding behavior with .bind
and & attr
to specify the binding type:
Remember, interpolation and keyword binding achieve similar results, and there should be no noticeable difference in performance or features. Choose the syntax based on your preference and the specific requirements of your project.
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.
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.
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:
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.
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.
Custom Attribute Instance Similarly, custom-attribute.ref="expression"
can reference a custom attribute's component instance (view-model).
Controller Instance For more advanced scenarios, controller.ref="expression"
creates a reference to a custom element's controller instance.
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.
Leveraging template references can greatly simplify interactions with elements, particularly when integrating with libraries that require direct DOM element references. This approach promotes cleaner and more maintainable code by reducing reliance on direct DOM queries.
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.
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.
isNaN
Display content conditionally based on numeric checks.
RegExp
Use the RegExp
constructor to create dynamic regular expressions for data validation or manipulation.
Object
Access properties dynamically on an object using the Object
constructor.
Set
Demonstrate set operations like union, intersection, or difference.
encodeURI
and decodeURI
Manipulate URL strings by encoding or decoding them.
Intl.NumberFormat
Format numbers using Intl.NumberFormat for localization.
Array
Demonstrate 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.
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.
By default, Aurelia provides mapping for all lower case a-z letters in both keycode and leter so both :ctrl+a
and :ctrl+97
works. For upper case letter, only keycode mapping is provided, for example: :65
for upper letter A works.
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.
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.
You could then display this value using its camelCase variant:
You can bind to variable values in a <let>
too:
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.
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.
The following example demonstrates a method fetchAdvice bound to the promise.bind
attribute. It uses then
and catch
to handle resolved data and errors.
The i
variable triggers a method call in the template, as Aurelia considers method calls pure and re-invokes them only if their parameters change.
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.
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.
When using promise.bind
within a repeat.for
, it's recommended to use a let
binding to create a scoped context.
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.
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.
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
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
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
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:
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
Update after typing stopped for 850ms
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
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
Multiple events are supported:
Update with multiple events
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
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
With the oneTime
binding behavior you can specify that string interpolated bindings should happen once. Simply write:
One-time String Interpolation
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
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
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
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
Using self-binding behavior
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.
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.
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.
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.
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.
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.
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.
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?
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.
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.
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
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.bind
The 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:
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 else
Aurelia enables if/else
structures in the view, similar to conditional statements in JavaScript. The else
binding must immediately follow an element with if.bind
:
This snippet displays a welcome message for authenticated users and a login prompt for others.
Caching Behavior: By default, if.bind
caches the view and view model of the element it's applied to. While caching can improve performance by reusing elements rather than recreating them, it may lead to unexpected behavior if you're not anticipating this. If state management becomes an issue, you may disable caching with the verbose syntax:
In this code, value.bind
is the condition, and cache: false
disables caching. Use this feature judiciously, as excessive use can impact performance.
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.bind
The 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.
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.bind
For 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:
Displaying a message based on the order status with if.bind
can become unwieldy. Instead, switch.bind
offers a concise and clear approach:
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:
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
:
When orderStatus
is Received
, both the "Order received." and "Order is being processed." messages will be displayed because of the fall-through
attribute.
By default, fallThrough
is false
. If you want a case to fall through, you must explicitly set fall-through.bind="true"
.
You can use the shorthand fall-through="true"
instead of binding, which will be interpreted as boolean values.
switch.bind
Aurelia'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:
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.bind
switch.bind
can be combined with au-slot
to project content into custom elements conditionally:
In this case, the custom element foo-bar
will project different messages based on the status
value.
switch.bind
switch.bind
can be nested within itself for complex conditional logic:
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:
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.
A developer guide for enabling SVG binding in the Aurelia.
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.
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:
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:
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:
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.
You can even bind to other attributes on form elements such as the placeholder
attribute.
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).
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"
.
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"
.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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:
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.
Binding behaviors are a category of view resources, just like value converters, custom attributes and custom elements. Binding behaviors are most like in that you use them declaratively in binding expressions to affect the binding.
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 , The debounce
binding behavior supports this scenario via signal. These signals can be added via the 2nd parameter, like the following example:
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 .
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 .
On a simplistic level, custom attributes resemble quite a lot. They can have , and they use classes for their definitions.
Want to learn more about bindable properties and how to configure them? Please reference the .
Many of the concepts discussed here assume knowledge of how Aurelia's template and binding syntax work. We recommend reading the section before continuing with this section if you are new to Aurelia.
class.bind="someString"
string
'col-md-4 bg-${bgColor}'
class="${someString}"
string
col-md-4 ${someString}
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.for
You 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.for
Aurelia'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.
Aurelia cannot observe changes to arrays using the array[index] = value
syntax. To ensure that Aurelia can observe the changes on your array, use the Array methods: Array.prototype.push
, Array.prototype.pop
, and Array.prototype.splice
.
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 Value Converter 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.
When creating utility value converters and other resources, we recommend globally registering them using Aurelia's DI. You can learn how to use Dependency Injection here.
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.
Methods on array that will create an array subscription
map
filter
includes
indexOf
lastIndexOf
findIndex
find
flat
flatMap
join
reduce
reduceRight
slice
some
Methods that trigger self-mutation like sort
/splice
/push
/pop
/shift
/unshift
/reverse
will not result in a subscription. It's unclear when and how to refresh the binding.
For sorting, it is recommended that we create a new array with slice
before sorting: items.slice(0).sort(...)
since sort()
mutates the existing array and could sometimes make the outcome confusing to follow.
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.
includes
Assign a class to an element if an array includes a specific item.
find
Display 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.
flat
Flatten a nested array and display its contents.
Use flat
to create a flattened list of attributes from an array of objects.
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.
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.
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:
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:
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:
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:
Dependencies can also be declared within the template using the <import>
tag or globally registered through Aurelia's Dependency Injection layer.
Aurelia provides an API for creating components programmatically, which is especially useful for testing.
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.
The file name determines the component's tag name. For example, a file named app-loader.html
would be used as <app-loader></app-loader>
.
For instance, an HTML-only loader component might look like this:
To use this component, import and reference it:
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:
Here's how you would use it:
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:
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:
For more on working with Aurelia's Dependency Injection and registering dependencies, see the Dependency Injection documentation.
To use a component within a specific template, import it using the <import>
tag:
To use a component but with an alias, import it using the <import>
tag, together with the as
attribute for the new name:
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:
If there are multiple resource exports with the same resource name (an element and an attribute with the same foo
name, for example), the alias will be applied to both of them.
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:
The @containerless
decorator is an alternative way to indicate a containerless component:
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:
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.
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.
This will allow our component to be passed in values. Our specified bindable property here is called loading
and can be used like this:
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.
As seen in the following example, you can also bind values without the loading.bind
part.
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.
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:
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
Please consult the binding modes documentation below to learn how to change the binding modes. By default, the binding mode for bindable properties will be one-way
You can change the name of the callback that is fired when a change is made @bindable({ callback: 'propChanged' })
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).
Bindable properties without an mode
explicitly set will be one-way
by default. You can also explicitly specify the binding mode.
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.
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:
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.
When using .bind
for input/form control values such as text inputs, select dropdowns and other form elements. Aurelia will automatically create a two-way binding relationship. So, the above example using a text input can be rewritten to be value.bind="myVal"
, and it would still be a two-way binding.
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
.
Suppose you have a carousel
component in which you want to enable navigator
feature for it.
In version two, you can easily implement such a capability with the set
feature.
Define your property like this:
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
Now, we should set truthyDetector
function as follows:
Although, there is another way to write the functionality too:
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:
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:
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.
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.
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.
The rest of the document is based on TypeScript examples. However, we trust that you can transfer that knowledge to your JavaScript codebase if necessary.
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.
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.
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.
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
.
Aurelia2 already exposes a noop
function saving your effort to write such boring functions.
When using TypeScript, usages of union types are not rare. However, using union types for @bindable
will deactivate the auto-coercion.
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
.
However, using a setter would be more straightforward to this end.
Even though using a noop
function for set
function is a straightforward choice, Object
can also be used for type
in the bindable definition to disable the auto-coercion for selective @bindable
s (that is when the automatic type-coercion is enabled).
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
with the template
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.
And the usage of our component would look like this:
to be repeated like this inside:
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:
, 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:
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.
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
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.
It'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:
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.
What attributes are captured
Everything except the template controller and custom element bindables are captured.
A usage example is as follows:
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:
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.
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.
Every lifecycle callback is optional. Implement whatever makes sense for your component, but don't feel obligated to implement any of them if they aren't needed for your scenario. Some of the lifecycle callbacks make sense to implement in pairs (binding/unbinding
, attaching/detaching
) to clean up any resources you have allocated.
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
All arguments on these callback lifecycle methods are optional and, in most cases, will not be needed.
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.
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".
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".
This is the last opportunity to add DI registrations specifically for child components in this container or any other way, affecting what is rendered and how it is rendered.
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.
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.
This is a good place to perform any work or change anything your view would depend on because data still flows down synchronously. This is the best time to do anything that might affect children. We prefer using this hook over bound
, unless you specifically need bound
for a situation when binding
is too early.
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.
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.
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.
If you return a Promise
from this method, it will not suspend the binding/attaching of child components, but it will be awaited before the attached
hook is invoked.
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.
This is the best time to invoke code that requires measuring of elements or integrating a 3rd party JavaScript library that requires the whole component subtree to be mounted to the DOM.
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.
If you return a Promise
(for example, from an outgoing animation), it will be awaited before the element is detached. It will run in parallel with promises returned from the detaching
hooks of siblings/parents.
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.
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.
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.
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.
If your application uses CSS frameworks like Bootstrap, which rely on global styles, consider how Shadow DOM encapsulation may affect their behavior. The following sections guide managing global and shared styles.
To enable Shadow DOM after the initial setup, configure it in the main.ts
file:
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:
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.
The sharedStyles
property accepts an array, allowing you to include multiple shared stylesheets.
useShadowDOM
The useShadowDOM
decorator, imported from Aurelia, lets you enable Shadow DOM on a per-component basis. Without configuration options, it defaults to open
mode.
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.
The useShadowDOM
decorator also allows disabling Shadow DOM for a specific component by passing false
.
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.
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.
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:
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.
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.
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.
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:
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:
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.
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.
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.
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 create a binding command, we use the @bindingCommand
decorator with a command name on a class that implements the following interface:
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.
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:
instead of
We first create a class that implements the BindingCommandInstance
interface to do that.
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.
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.
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:
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:
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:
should be treated as:
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:
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
:
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:
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:
Similarly, examples for <ion-input>
and <paper-input>
:
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:
And with the above, your Aurelia application will get two way binding flow seamlessly:
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.
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.
Let us consider the following example.
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.
Following 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.
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.
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.
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.
Now with this information, we also have a new diagram.
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.
Typically the properties for the let
-bindings are view-only properties. It makes sense to have those properties in the overriding context.
Do you know that you can use to-binding-context
attribute in let
-binding to target the binding context instead of override context? Why don't you try <let foo.bind="42" to-binding-context></let>
and inspect the scope contexts by yourself?
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.
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.
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.
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.
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.
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).
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.
.
As expected, the example produces the following output.
Note 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.
Although 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.
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!
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.
Its parameters are as follows
Consider the following example:
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:
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
: "[(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.
Given the above example and the implementation, the parameters would have values like the following:
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:
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:
Locally
You may want to use it in a specific part of your application. You can introduce it through dependencies
.
Import from somewhere else:
Define it inline:
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>
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.
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:
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.
Now, to use our element with a named slot, you can do this:
A slot can display default content when nothing is explicitly projected into it. Fallback content works for default and named slot elements.
The <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:
@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:
{% code title="my-app.html" overflow="wrap" lineNumbers="true" }
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 usageNote: the @children
decorator wont update if the children of a slotted node change — only if you change (e.g. add or delete) the actual nodes themselves.
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.
An obvious question might be, "Why not simply 'turn off' shadow DOM, and use the slot
itself"? We feel that goes opposite to Aurelia's promise of keeping things as close to native behavior as possible. Moreover, using a different name like au-slot
makes it clear that the native slot is not used in this case. However, still brings slotting behavior to use.
If you have used the replaceable
and replace part
before or with Aurelia1, it is replaced with au-slot
.
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.
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:
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.
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.
The followingrk would be logged to the console for the instances of my-element
.
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.
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.
Let's consider the following example with interpolation. This is the same example as before, but this time without projection.
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 @bindable
s in custom elements.
$host
The outer custom element can access the inner custom element's scope using the $host
keyword, as shown in the following example.
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.
Let's consider another example of $host
which highlights the communication between the inside and outside of a custom element that employs <au-slot>
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 last example is also interesting from another aspect. It shows that many parts of the grid can be replaced with projection while working with a grid. This includes the header of the grid (au-slot="header"
), the template column of the grid (au-slot="content"
), or even the whole grid itself (au-slot="grid"
).
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.
This is useful for many cases. One evident example would a 'tabs' custom element.
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.
<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:
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:
### 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:
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:
An example of using slotchange
behavior may look like the following:
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.
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]
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.
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.
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.
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 transformTitle
method 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.
Are you trying to set the title using the Aurelia i18n package? Visit the section on configuring translated router titles here.
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)
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
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.
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.
By specifying the viewport
property on a route, we can tell it to load into a specific route.
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.
If you have more than a few routes, it might be best practice to write them in a separate file and then import them inside your application.
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.
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.
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.
Router lifecycle hook methods are all completely optional. You only have to implement the methods you require. The router will only call a method if it has been specified inside of your routable component. All lifecycle hook methods also support returning a promise and can be asynchronous.
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.
If you were loading data from an API based on values provided in the URL, you would most likely do that inside canLoad
if the view is dependent on the data successfully loading.
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.
If you are loading data from an API based on values provided in the URL and the rendering of this view is not dependent on the data being successfully returned, you can do that inside of load
.
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 loading
lifecycle 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.
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:
Then, intuitively, we would write the following template:
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.
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.
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.
With this custom mapping registered, we can expect the following to work.
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.
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.
A similar example can be seen in action below.
Furthermore, the constructor is where you handle the injection of dependencies using dependency injection. You will learn about DI in the , but here is a basic example of where the constructor is used.
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 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 for more details.
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 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.
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 is used to determine the binding mode, the target property name, etc. (for more information, refer to the ). In short, here comes your logic to convert the attribute information into a binding instruction.
Microsoft FAST text-field
element:
Ionic ion-input
element:
Polymer paper-input
element:
Combining the examples in the two sections above into some more complete code block example, for :
One way to think about expression and binding context is in terms of functions and binding those functions with an execution context (Refer: ).
As the assignment is made pre-binding phase (created
hook in the example above), the context 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 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 template controller.
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 , and thus not repeated here.
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 instead.
Note that projection for the name is provided once, but it gets duplicated in 2 slots. You can also see this example in action .
If you are unfamiliar with the au-slot
then visit the . 'processContent' can be very potent with 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.
If you are looking for details on configuring the router (set titles, handle unknown routes, etc.), please see the section at the end of this guide.
The following getting started guide assumes you have an Aurelia application already created. If not, to get Aurelia installed in minutes.
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.
Can't find what you're looking for in this section? We have a section detailing many tasks for working with the router, from passing data between routes to route guards.
This section is not for catch-all/404 routes. If you are using configured routing, you are looking for the .
Still, confused or need an example? You can find an example application with routing over on GitHub .
Parameters are supplied to canLoad
and loading
router lifecycle callbacks as the first argument. They are passed as an object with key/value pairs. Please consult the section to learn how to access them.
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 , 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.
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 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.
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.
rawName
Left-side of assignment.
rawValue
Right-side of assignment.
parts
The values of PARTs of your pattern without symbols.
@children() prop
Use default options, observe mutation, and select all elements
@children('div') prop
Observe mutation, and select only div
elements
@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
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
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
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.
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.
As outlined in the Creating Routes section, routes can be specified using the routes
decorator or the static routes
property.
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.
You can have more than one parameter (as many as you like):
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.
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.
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.
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.
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:
As you might expect, these events are named in an intuitive way depending on the action taking place inside the router.
You will want to listen to the end, cancel and error navigation events if you're relying on displaying and hiding parts of the UI based on the router to ensure you're checking for a true "done" state.
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.
The load
method can accept a simple string value allowing you to navigate to another component without needing to supply configuration options.
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:
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:
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.
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.
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.
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:
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.
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.
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.
Please note that you are not recommended to use global lifecycle hooks when you can avoid them, as they are run for each component, the same as you would use inside.
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:
And this 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 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.
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.
It is also permitted to define more than one hook per shared hook class:
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 here.
To do this tutorial, you'll need a working Aurelia application. We highly recommend following the Quick Start guide to scaffold an application. However, for this tutorial, we have a starter Aurelia 2 application 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 Aurelia Fetch Client 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 can be seen here (or below).
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.
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.
We 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 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.
Router lifecycle hook methods are all completely optional. You only have to implement the methods you require. The router will only call a method if it has been specified inside of your routable component. All lifecycle hook methods also support returning a promise and can be asynchronous.
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.
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.
In case you are looking for the global/shared routing hooks, there is a separate documentation section dedicated for that.
canLoad
The 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.
You can also see this example in action below.
canLoad
Not 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.
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.
Note that you can also choose to return a sibling navigation instructions. This can be done by returning an array of navigation instructions.
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.
You can also see the example in action below.
loading
The 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.
canUnload
The 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.
You can see this example in action below.
unloading
The 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.
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.
Learn 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.
useUrlFragmentHash
If 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 MDN) 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.
basePath
Configuring 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 base#href
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 external
attribute. 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 default behavior of building the title. 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 data
property 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 useHref
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 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 external
attribute.
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
.
push
This 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.
replace
This 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.
none
Use 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 navigation options 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 load
custom attribute 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.
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.
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 you can map multiple paths to a single component. Although these paths can be thought of as aliases, multiple paths, in combination with path parameters gets interesting. Another way of creating aliases is to use the redirectTo
configuration option.
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.
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.
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.
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
.
When a given URL matches one such route, the parameter value is made available in the canLoad
, and load
routing hooks.
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
.
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.
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.
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
.
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.
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.
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.
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.
You can see this action below.
Note that redirection also works when there are multiple paths/aliases defined for the same component.
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.
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.
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.
It is recommended that you configure a fallback
at the root to handle the navigation to un-configured routes gracefully.
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.
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.
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.
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 href
s 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.
You can see this in action below.
If you are using TypeScript, ensure that the module
property set to esnext
in your tsconfig.json
to support inline import statements.
Components can be configured using only the custom-element name of the component.
However, when configuring the route this way, you need to register the components to the DI.
You can see this configuration in action below.
Components can be configured using a function that returns a class.
You can see this configuration in action below.
Components can be configured using custom element definition.
You can see this configuration in action below.
Components can be configured using custom element instance.
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
.
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.
To know more about the router API refer this section.
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.
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.
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
.
This can be seen in action below.
You can also use the @route
decorator and the getRouteConfig
together.
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.
Learn about viewports in Router-Lite and how to configure hierarchical routing.
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.
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.
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.
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.
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.
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.
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.
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).
You can see in the live example below that this fixes the duplication issue.
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
.
In the following example, we have the main
viewport for our main content and then another viewport called sidebar
for our sidebar content.
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:
The live example below shows this.
Note the load
attributes in the anchor
elements.
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.
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 anchor
s in the example that show that the viewport names can now be dropped from the routing instructions.
used-by
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.
The live example below shows this in action
Note how clicking the links load the components also in the first viewport without any value for the used-by
.
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.
The example below shows this in action.
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.
You can also see this 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
.
router-lite
To use the router-lite
, we have to register it with Aurelia. We do this at the bootstrapping phase.
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.
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
.
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:
The examples are created using StackBlitz. Sometimes, you need to open the examples in a new tab to see changes in the URL, title etc. To this end, copy the URL appearing on the address bar on the right pane and open that in a new tab.
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.
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.
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.
href
custom attributeTo 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 attributeTo 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.
params
Using 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.
route
You can see this in action below.
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.
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.
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
This can be seen in action in the live example below.
Using import()
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
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
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
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.
Learn about how to subscribe to and handle router events.
The router emits the following 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.
To this end, inject the IRouterEvents
and use the IRouterEvents#subscribe
.
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.
This is shown in action below.
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.
To start an Aurelia application, create a new Aurelia()
object with a target host
and a root component
and call 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.
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:
src/main.ts:
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).
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.
It might be normal to think that the default selection of the replace
transition plan when the parameter changes, to be an overkill and the default selection should have been invoke-lifecycles
instead. As a matter of fact that's the default option in Aurelia1 as well as in earlier versions of Aurelia2. However, as understood from the user-voices that replace
would in this case cause less surprises. Hence the default behavior is changed to replace
.
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.
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.
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.
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.
How to implement router "guards" into your applications to protect routes from direct access.
If you worked with Aurelia 1, you might know these by their previous name: router pipelines.
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.
The example we are going to build in this section is just a toy example. For your production code, perform due diligence to evaluate the potential security threats.
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.
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 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.
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.
Lastly, the shared lifecycle hooks are invoked before the instance lifecycle hooks.
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 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 the
host` 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 enhance
API 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.
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.
Note that in the example above we aren't dealing with async routing. Therefore, for that example waiting the INavigationModel#resolve()
can be avoided.
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.
The <au-viewport>
element, or commonly referred to as viewport (not to confuse with ), is the "outlet", where the router-lite attaches/loads the components. For a basic example of viewport, please refer the . 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 , a component can define a set of children routes (using ). The child routes can also in turn define children routes of there own. Such route configuration are commonly known as hierarchical route configuration.
This is happening due to the default value of the 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.
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 .
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 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.
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 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.
As seen in , viewports can be named. It is particularly useful when there are multiple present. Note that specifying a value for the name
attribute of viewport is optional, and the default value is simply 'default'
.
For more details about navigating and instructions for router-lite, please refer the .
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 .
The used-by
attribute on the au-viewport
component can be thought of as (almost) the parallel of the 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.
Although the used-by
attribute feels like a markup alternative of the 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.
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 .
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 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 . 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.
Please note that in Aurelia2 there are two routers, namely and @aurelia/router-lite
(this one). The router-lite one is smaller in size, supports only configured routing, and does not support direct routing, as facilitated by @aurelia/router
. Choose your router depending on your need.
The following getting started guide assumes you have an Aurelia application already created. If not, to get Aurelia installed in minutes.
To know more about the different configuration options for router-lite, please refer the on that topic.
To know more about configuring routes, please refer to the respective .
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 , 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 at your disposal.
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 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.
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.
By 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 .
Although 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.
The 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.
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.
Note that the also offers a .
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.
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.
Similar to , for load
you can use a function that returns a class as routing instruction. This looks like as follows.
Similar to , for load
you can use an import()
statement to import a module. This looks like as follows.
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.
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.
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.
Fallback using the
Fallback using the
You can use the lifecycle hooks ( and ) 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.
au:router:location-change
: Emitted when the browser location is changed via the and events.
The events can be subscribed to using the . However, there is another type-safe alternative to that.
Transition plan can be configured using the transitionPlan
property in the . The allowed values are replace
, invoke-lifecycles
, none
or a function that returns one of these values.
When the transitionPlan
property in the is not configured, router-lite uses replace
when the parameters are changed and none
otherwise.
This can be interesting when dealing with , as you can select different transition plan for different siblings.
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.
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.
To know more about the order of invocation, please refer the respective .
The lifecycle hooks can be registered either globally (as it is done in the or as .
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.
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 .
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.
Note that apart from , all other properties of the route object are same as the corresponding configured route.
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.
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:
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:
You do not have to check if newValue
and oldValue
are different. The change handler will not be called if you assign a value the property already has.
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:
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.
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:
The property coord
of a MouseTracker
instance will be turned into a reactive property and is also aware of effect function dependency tracking.
Properties decorated with @observable
and any proxy based property accesses will be tracked as dependencies of the effect
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:
Getting through injection:
Or
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:
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:
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:
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:
The following section gives some examples of what it looks like when combining @observable
and run effect.
Now whenever the user moves the mouse around, a log will be added to the console with the coordinate of the mouse.
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:
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:
With a custom element as a view model, all standard lifecycles and activate
will be called during the composition.
activate
will be called right after constructor
, before all other lifecycles.
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 without a custom element as a the component view model, the resulted component will use the parent scope as its scope unless scope-behavior
is set to scoped
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.bind
activate
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
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
Decoratorinject
Propertyall
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
Decoratorinject
Propertyoptional
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
Decoratorinject
Propertyfactory
ResolverThe factory
resolver provides a function to create instances of a service, allowing for more control over the instantiation process.
@inject
Decoratorinject
PropertynewInstanceForScope
ResolverUse newInstanceForScope
when you need a unique instance of a service within a particular scope, such as a component or sub-container.
@inject
Decoratorinject
PropertynewInstanceOf
ResolverThe newInstanceOf
resolver ensures that a fresh instance of a service is created each time, regardless of other registrations.
@inject
Decoratorinject
PropertyYou 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.
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.
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:
Sometimes it's more desirable to work with a higher level API, for this consider using watch
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.
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:
Any decorator on a class will trigger TypeScript to emit type metadata, which Aurelia's DI can use.
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.
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 MS Fast integration, building plugins, and the section on using the template compiler.
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 here.
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.
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.
Intended usages
The @watch
decorator can only be used on custom element and attribute view models.
Corresponding watchers of @watch
decorator will be created once, bound after binding
, and unbound before unbinding
lifecycles. This means mutation during binding
/ after unbinding
won't be reacted to, as watchers haven't started or have stopped.
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.
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:
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:
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.
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.
During
binding
lifecycle, bindings created by@watch
decorator haven't been activated yet, which means mutations won't be reacted to:
There will be no log in the console.
During
bound
lifecycle, bindings created by@watch
decorator have been activated, and mutations will be reacted to:
There will be 1 log in the console that looks like this: packages changes: 0 -> 1
.
Other lifecycles that are invoked after binding
and before unbinding
are not sensitive to the working of the @watch
decorator, and thus don't need special mentions. Those lifecycles are attaching
, attached
, and detaching
.
During
detaching
lifecycle, bindings created by@watch
decorator have not been de-activated yet, and mutations will still be reacted to:
There will be 1 log in the console that looks like this: packages changes: 0 -> 1
.
During
unbinding
lifecycle, bindings created by@watch
decorator have been deactivated, and mutations won't be reacted to:
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:
An example is:
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.
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 ===
.
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:
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.
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.
The Event Aggregator is not for listening to native events. For those, you still use addEventListener
and detachEventListener
the event aggregator is a pub/sub package for publishing and subscribing to custom events.
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.
The Event Aggregator provides a subscription method to subscribe to published events.
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.
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).
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.
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 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
.
We aim to test that the PersonDetail
component renders the expected text when provided with name
and age
properties.
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:
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:
To test this component, you can create a mock PersonFormatter
and register it with the Aurelia container:
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.
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.
We highly recommend using the task queue to replace existing uses of setTimeout
and setInterval
for better-performing applications.
setTimeout
(Synchronous)Instead of `setTimeout, ' the TaskQueue offers a more reliable way to queue tasks without delay.
If you were to use a native setTimout
, it would look like this:
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.
The TaskQueue can mimic setInterval
functionality, offering more control and reliability.
For tasks that need to synchronize with the browser's repaint, domWriteQueue
is a safer alternative to requestAnimationFrame
.
For continuous animations, the TaskQueue can be used to create a loop, similar to requestAnimationFrame
.
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.
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.
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:
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:
With 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.
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.
Before writing the test, ensure your environment is correctly set up for testing. Refer to the section for details on how to initialize the Aurelia testing platform.
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.
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:
In this example, we scope our logger to our component. But scoping is optional, and the logger can be used without using scopeTo
however, 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.
Just like console.log
you can also pass in values such as strings, booleans, arrays and objects.
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.
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:
This plugin is in development, expect unstability.
Install via npm
Load the plugin
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.
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:
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:
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'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:
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:
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:
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 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.
For simplicity, all the examples below define elements at the start of an application, but they can be defined at any time.
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:
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.
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 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+
Go to a folder that you want to make the project, for example my-plugin
Create a packages
folder and package.json
inside it.
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.
After 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
As our core package, it has no dependency.
bootstrap-v5
Go to its package.json
and change the name to
Then, add the following dependencies:
demo
Go to its package.json
and change the name to
Then, add the following dependencies:
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.
Go 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.
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.
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:
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:
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.
Create new index.ts
file inside bootstrap-v5-core
package too.
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.
ViewModel
Create bs-button.ts
file.
As you can see we are able to access to plugin options easy via ctor
(DI) and react appropriately to its values.
In 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.
Create src/index.ts
file.
Create new index.ts
file inside bootstrap-v5
package.
Open demo
package and go to the src
and update main.ts
.
Importing is available for whole components
Or just a component
To register your components you should add them to register
method.
We support configuration so we should introduce it to register
method too.
Now, You are able to use your bs-button
inside src/my-app.html
.
To run the demo
easily, go to the my-plugin
root folder and add the following script section to the package.json
.
Then, call the command
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:
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.
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.
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.
Good tests cover a range of scenarios, including expected successes, expected failures, and edge cases. This comprehensive approach ensures your value converter handles all types of inputs gracefully.
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.
Before writing tests, make sure to set up the test environment as described in the .
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.
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.