Cheat sheet

Forgot the syntax for bindings? Need to know how to create a custom attribute? This article contains answers to questions like those as well as a bunch of quick snippets for common tasks..

Configuration and Startup

Standard Startup Configuration

export function configure(aurelia) {
    aurelia.use
      .standardConfiguration()
      .developmentLogging();
  
    aurelia.start().then(() => aurelia.setRoot());
}

Explicit Startup Configuration

 
  import {LogManager} from 'aurelia-framework';
  import {ConsoleAppender} from 'aurelia-logging-console';
  
  LogManager.addAppender(new ConsoleAppender());
  LogManager.setLevel(LogManager.logLevel.debug);
  
  export function configure(aurelia) {
    aurelia.use
      .defaultBindingLanguage()
      .defaultResources()
      .history()
      .router()
      .eventAggregator();
  
    aurelia.start().then(() => aurelia.setRoot('app', document.body));
  }

Configuring a Feature

Installing a Plugin

Creating Components

UI components consist of two parts: a view-model and a view. Simply create each part in its own file. Use the same file name but different file extensions for the two parts. For example: hello.js and hello.html.

Explicit Configuration

The Component Lifecycle

Components have a well-defined lifecycle:

  1. constructor() - The view-model's constructor is called first.

  2. created(owningView: View, myView: View) - If the view-model implements the created callback it is invoked next. At this point in time, the view has also been created and both the view-model and the view are connected to their controller. The created callback will receive the instance of the "owningView". This is the view that the component is declared inside of. If the component itself has a view, this will be passed second.

  3. bind(bindingContext: Object, overrideContext: Object) - Databinding is then activated on the view and view-model. If the view-model has a bind callback, it will be invoked at this time. The "binding context" to which the component is being bound will be passed first. An "override context" will be passed second. The override context contains information used to traverse the parent hierarchy and can also be used to add any contextual properties the component wants. It should be noted that when the view-model has implemented the bind callback, the data-binding framework will not invoke the changed handlers for the view-model's bindable properties until the "next" time those properties are updated. If you need to perform specific post-processing on your bindable properties, when implementing the bind callback, you should do so manually within the callback itself.

  4. attached() - Next, the component is attached to the DOM (in document). If the view-model has an attached callback, it will be invoked at this time.

  5. detached() - At some point in the future, the component may be removed from the DOM. If/When this happens, and if the view-model has a detached callback, this is when it will be invoked.

  6. unbind() - After a component is detached, it's usually unbound. If your view-model has the unbind callback, it will be invoked during this process.

Dependency Injection

Declaring Dependencies

Using Resolvers

Available Resolvers

  • Lazy - Injects a function for lazily evaluating the dependency.

    • ex. Lazy.of(HttpClient)

  • All - Injects an array of all services registered with the provided key.

    • ex. All.of(Plugin)

  • Optional - Injects an instance of a class only if it already exists in the container; null otherwise.

    • ex. Optional.of(LoggedInUser)

  • Parent - Skips starting dependency resolution from the current container and instead begins the lookup process on the parent container.

    • ex. Parent.of(MyCustomElement)

  • Factory - Used to allow injecting dependencies, but also passing data to the constructor.

    • ex. Factory.of(CustomClass)

  • NewInstance - Used to inject a new instance of a dependency, without regard for existing instances in the container.

    • ex. NewInstance.of(CustomClass).as(Another)

Explicit Registration

Templating Basics

A Simple Template

Requiring Resources

circle-info

Invalid Table Structure When Dynamically Creating Tables

When the browser loads in the template it very helpfully validates the structure of the HTML, notices that you have an invalid tag inside your table definition, and very unhelpfully removes it for you before Aurelia even has a chance to examine your template.

circle-exclamation

Use of the as-element attribute ensures we have a valid HTML table structure at load time, yet we tell Aurelia to treat its contents as a different tag.

Compose an existing object instance with a view.

For the above example we can then programmatically choose the embedded template based on an element of our data:

template_A.html

template_B.html

Note that when a containerless attribute is used, the container is stripped after the browser has loaded the DOM elements, and as such this method cannot be used to transform non-HTML compliant structures into compliant ones!

Illegal Table Code

Correct Table Code

Illegal Select Code

Correct Select Code

Databinding

bind, one-way, two-way & one-time

Use on any HTML attribute.

  • .bind - Uses the default binding. One-way binding for everything but form controls, which use two-way binding.

  • .one-way - Flows data one direction: from the view-model to the view.

  • .two-way - Flows data both ways: from view-model to view and from view to view-model.

  • .one-time - Renders data once, but does not synchronize changes after the initial render.

Data Binding Examples

circle-info

At the moment inheritance of bindables is not supported. For use cases where class B extends A and B is used as custom Element/Attribute @bindable properties cannot be defined only on class A. If inheritance is used, @bindable properties should be defined on the instantiated class.

delegate, trigger

Use on any native or custom DOM event. (Do not include the "on" prefix in the event name.)

  • .trigger - Attaches an event handler directly to the element. When the event fires, the expression will be invoked.

  • .delegate - Attaches a single event handler to the document (or nearest shadow DOM boundary) which handles all events of the specified type, properly dispatching them back to their original targets for invocation of the associated expression.

circle-info

The $event value can be passed as an argument to a delegate or trigger function call if you need to access the event object.

Event Binding Examples

call

Passes a function reference.

ref

Creates a reference to an HTML element, a component or a component's parts.

  • ref="someIdentifier" or element.ref="someIdentifier" - Create a reference to the HTMLElement in the DOM.

  • attribute-name.ref="someIdentifier"- Create a reference to a custom attribute's view-model.

  • view-model.ref="someIdentifier"- Create a reference to a custom element's view-model.

  • view.ref="someIdentifier"- Create a reference to a custom element's view instance (not an HTML Element).

  • controller.ref="someIdentifier"- Create a reference to a custom element's controller instance.

String Interpolation

Used in an element's content. Can be used inside attributes, particularly useful in the class and css attributes.

Binding to Select Elements

A typical select element is rendered using a combination of value.bind and repeat. You can also bind to arrays of objects and synchronize based on an id (or similar) property.

Basic Select

Select With Object Array

Select with Object Id Sync

Basic Multi-Select

Multi-Select with Object Array

Binding Radios

Binding Checkboxes

circle-exclamation

Binding innerHTML and textContent

triangle-exclamation
circle-exclamation

Binding Style

You can bind a css string or object to an element's style attribute. Use the style attribute's alias, css when doing string interpolation to ensure your application is compatible with Internet Explorer.

Illegal Style Interpolation

Declaring Computed Property Dependencies

Templating View Resources

Conditionally displays an HTML element.

Conditionally add/remove an HTML element

Conditionally add/remove a group of elements

Creating new component instance every time condition changes

Render an array with a template

Render a map with a template

Render a template N times

Contextual items available inside a repeat template:

  • $index - The index of the item in the array.

  • $first - True if the item is the first item in the array.

  • $last - True if the item is the last item in the array.

  • $even - True if the item has an even numbered index.

  • $odd - True if the item has an odd numbered index.

circle-info

Containerless Template Controllers

The if and repeat attributes are usually placed on the HTML elements that they affect. However, you can also use a template tag to group a collection of elements that don't have a parent element and place the if or repeat on the template element instead.

Dynamically render UI into the DOM based on data

Composing a view only, inheriting the parent binding context

Compose an existing object instance with a view

Routing

Basic Route Configuration

Route Pattern Options

  • static routes

    • ie 'home' - Matches the string exactly.

  • parameterized routes

    • ie 'users/:id/detail' - Matches the string and then parses an id parameter. Your view-model's activate callback will be called with an object that has an id property set to the value that was extracted from the url.

  • wildcard routes

    • ie 'files*path' - Matches the string and then anything that follows it. Your view-model's activate callback will be called with an object that has a path property set to the wildcard's value.

The Route Screen Activation Lifecycle

  • canActivate(params, routeConfig, navigationInstruction) - Implement this hook if you want to control whether or not your view-model can be navigated to. Return a boolean value, a promise for a boolean value, or a navigation command.

  • activate(params, routeConfig, navigationInstruction) - Implement this hook if you want to perform custom logic just before your view-model is displayed. You can optionally return a promise to tell the router to wait to bind and attach the view until after you finish your work.

  • canDeactivate() - Implement this hook if you want to control whether or not the router can navigate away from your view-model when moving to a new route. Return a boolean value, a promise for a boolean value, or a navigation command.

  • deactivate() - Implement this hook if you want to perform custom logic when your view-model is being navigated away from. You can optionally return a promise to tell the router to wait until after you finish your work.

circle-exclamation

The params object will have a property for each parameter of the route that was parsed, as well as a property for each query string value. routeConfig will be the original route configuration object that you set up. routeConfig will also have a new navModel property, which can be used to change the document title for data loaded by your view-model. For example:

Route Params and NavModel

Conventional Routing

Customizing The Navigation Pipeline

circle-exclamation

Reusing an Existing View Model

Since the view model's navigation lifecycle is called only once, you may have problems recognizing that the user switched the route from Product A to Product B (see below). To work around this issue implement the method determineActivationStrategy in your view model and return hints for the router about what you'd like to happen. Available return values are replace and invoke-lifecycle. Remember, "lifecycle" refers to the navigation lifecycle.

Router View Model Activation Control

circle-info

Alternatively, if the strategy is always the same and you don't want that to be in your view model code, you can add the activationStrategy property to your route config instead.

Rendering multiple ViewPorts

circle-info

If you don't name a router-view, it will be available under the name 'default'.

Multi-ViewPort View

Multi-ViewPort View-Model

Generating Route URLs

Custom Attributes

Simple Attribute Declaration

Simple Attribute Use

Options Attribute Declaration

Options Attribute Use

Dynamic Option Attribute Declaration

Dynamic Option Attribute Use

Bindable Signature (Showing Defaults)

Template Controller Attribute Declaration

Template Controller Attribute Use

Custom Elements

Custom Element View-Model Declaration

Custom Element View Declaration

Custom Element Use

Custom Element Without View-Model Declaration

Aurelia will not search for a JavaScript file if you reference a component with an .html extension.

Custom Element Variable Binding

It's worth noting that when binding variables to custom elements, use camelCase inside the custom element's View-Model, and dash-case on the html element. See the following example:

Custom Element Options

  • @children(selector) - Decorates a property to create an array on your class that has its items automatically synchronized based on a query selector against the element's immediate child content. Does not work with @containerless(), see below.

  • @child(selector) - Decorates a property to create a reference to a single immediate child content element. Does not work with @containerless(), see below.

  • @processContent(false|Function) - Tells the compiler that the element's content requires special processing. If you provide false to the decorator, the compiler will not process the content of your custom element. It is expected that you will do custom processing yourself. But, you can also supply a custom function that lets you process the content during the view's compilation. That function can then return true/false to indicate whether or not the compiler should also process the content. The function takes the following form function(compiler, resources, node, instruction):boolean

  • @useView(path) - Specifies a different view to use.

  • @noView() - Indicates that this custom element does not have a view and that the author intends for the element to handle its own rendering internally.

  • @inlineView(markup, dependencies?) - Allows the developer to provide a string that will be compiled into the view.

  • @useShadowDOM(options?: { mode: 'open' | 'closed' }) - Causes the view to be rendered in the ShadowDOM. When an element is rendered to ShadowDOM, a special DOMBoundary instance can optionally be injected into the constructor. This represents the shadow root. Does not work with @containerless(), see below.

  • @containerless() - Causes the element's view to be rendered without the custom element container wrapping it. This cannot be used in conjunction with @child, @children or @useShadowDOM decorators. It also cannot be uses with surrogate behaviors. Use sparingly.

SVG Elements

SVG (scalable vector graphic) tags can support Aurelia's custom element <template> tags by nesting the templated code inside a second <svg> tag. For example if you had a base <svg> element and wanted to add a templated <rect> inside it, you would first put your custom tag inside the main <svg> tag. Also, make sure the custom element class uses the @containerless() decorator.

Template Parts

Observable decorator

Aurelia exposes a decorator named observable to allow watching for changes to a property and reacting to them. By convention it will look for a matching method name Changed

The developer can also specify a different method name to use.

The Event Aggregator

If you include the aurelia-event-aggregator plugin using "basicConfiguration" or "standardConfiguration" then the singleton EventAggregator's API will be also present on the Aurelia object. You can also create additional instances of the EventAggregator, if needed, and "merge" them into any object. To do this, import includeEventsIn and invoke it with the object you wish to turn into an event aggregator. For example includeEventsIn(myObject). Now my object has publish and subscribe methods and can be used in the same way as the global event aggregator, detailed below.

Publishing on a Channel

Subscribing to a Channel

Publishing a Message

Subscribing to a Message Type

Last updated

Was this helpful?