Custom attributes
Learn how to build and enhance Aurelia 2 custom attributes, including advanced configuration, binding strategies, and accessing the host element.
Custom attributes in Aurelia empower you to extend and decorate standard HTML elements by embedding custom behavior and presentation logic. They allow you to wrap or integrate existing HTML plugins and libraries, or simply enhance your UI components with additional dynamic functionality. This guide provides a comprehensive overview—from basic usage to advanced techniques—to help you leverage custom attributes effectively in your Aurelia 2 projects.
Table of Contents
Introduction
Custom attributes are one of the core building blocks in Aurelia 2. Similar to components, they encapsulate behavior and style, but are applied as attributes to existing DOM elements. This makes them especially useful for:
Decorating elements with additional styling or behavior.
Wrapping third-party libraries that expect to control their own DOM structure.
Creating reusable logic that enhances multiple elements across your application.
Creating a Basic Custom Attribute
At its simplest, a custom attribute is defined as a class that enhances an element. Consider this minimal example:
When you apply a similar pattern using CustomElement instead, you are defining a component. Custom attributes are a more primitive (yet powerful) way to extend behavior without wrapping the entire element in a component.
Example: Red Square Attribute
This custom attribute adds a fixed size and a red background to any element it is applied to:
Usage in HTML:
The <import>
tag ensures that Aurelia’s dependency injection is aware of your custom attribute. When applied, the <div>
will render with the specified styles.
Explicit Custom Attributes
To gain finer control over your attribute’s name and configuration, Aurelia provides the @customAttribute decorator. This lets you explicitly define the attribute name and even set up aliases.
Explicit Attribute Naming
By default, the class name might be used to infer the attribute name. However, you can explicitly set a custom name:
Attribute Aliases
You can define one or more aliases for your custom attribute. This allows consumers of your attribute flexibility in naming:
Now the attribute can be used interchangeably using any of the registered names:
Single Value Binding
For simple cases, you might want to pass a single value to your custom attribute without explicitly declaring a bindable property. Aurelia will automatically populate the value property if a value is provided.
To further handle changes in the value over time, you can define the property as bindable:
Bindable Properties and Change Detection
Custom attributes often need to be configurable. Using the @bindable decorator, you can allow users to pass in parameters that change the behavior or style dynamically. In the following example, the background color is configurable:
You can extend this to support multiple bindable properties. For example, to also allow a dynamic size:
Options Binding for Multiple Properties
When you have more than one bindable property, you can use options binding syntax to bind multiple properties at once. Each bindable property in the view model corresponds to a dash-case attribute in the DOM. For instance:
The Aurelia binding engine converts the attribute names (e.g., color-square
) to the corresponding properties in your class.
Specifying a Primary Bindable Property
If one of your bindable properties is expected to be used more frequently, you can mark it as the primary property. This simplifies the syntax when binding:
With a primary property defined, you can bind directly:
Accessing the Host Element
A key aspect of custom attributes is that they work directly on DOM elements. To manipulate these elements (e.g., updating styles or initializing plugins), you need to access the host element. Aurelia provides a safe way to do this using dependency injection with INode
.
Note: While you can also use resolve(Element)
or resolve(HTMLElement)
, using INode
is safer in environments where global DOM constructors might not be available (such as Node.js).
Finding Related Custom Attributes
In complex UIs, you might have multiple custom attributes working together (for example, a dropdown with associated toggle buttons). Aurelia offers the CustomAttribute.closest
function to traverse the DOM and locate a related custom attribute. This function can search by attribute name or by constructor.
Example: Searching by Attribute Name
Example: Searching by Constructor
If you want to search based on the attribute’s constructor (for stronger typing), you can do so:
Lifecycle Hooks and Best Practices
Custom attributes, like components, have lifecycle hooks that let you run code at different stages of their existence:
bind() / unbind()
: Initialize or clean up data bindings.attached() / detached()
: Perform actions when the host element is attached to or removed from the DOM.
Example: Using Lifecycle Hooks
Best Practices:
Separation of Concerns: Keep your custom attribute logic focused on enhancing the host element, and avoid heavy business logic.
Performance: Minimize DOM manipulations inside change handlers. If multiple properties change at once, consider batching style updates.
Testing: Write unit tests for your custom attributes to ensure that lifecycle hooks and bindings work as expected.
Documentation: Comment your code and document the expected behavior of your custom attributes, especially if you provide aliases or multiple bindable properties.
Integrating Third-Party Libraries
Often, you’ll want to incorporate functionality from third-party libraries—such as sliders, date pickers, or custom UI components—into your Aurelia applications. Custom attributes provide an excellent way to encapsulate the integration logic, ensuring that the third-party library initializes, updates, and cleans up properly within Aurelia's lifecycle.
When to Use Custom Attributes for Integration
DOM Manipulation: Many libraries require direct access to the DOM element for initialization.
Lifecycle Management: You can leverage Aurelia's lifecycle hooks (
attached()
anddetached()
) to manage resource allocation and cleanup.Dynamic Updates: With bindable properties, you can pass configuration options to the library and update it reactively when those options change.
Example: Integrating a Hypothetical Slider Library
Consider a third-party slider library called AwesomeSlider
that initializes a slider on a given DOM element. Below is an example of how to wrap it in a custom attribute.
In place of our hypothetical AwesomeSlider
library, you can use any third-party library that requires DOM manipulation such as jQuery plugins, D3.js, or even custom UI components.
Last updated
Was this helpful?