The basics of the web-component plugin for Aurelia.
Introduction
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 to create Web Components that can be used in any framework or vanilla JavaScript application.
Installing The Plugin
To use the web components functionality, you need to install the @aurelia/web-components package:
npminstall@aurelia/web-components
The package provides the IWcElementRegistry interface which allows you to define web-component custom elements by calling the define method.
Basic Setup
To use web components in your Aurelia application, import the IWcElementRegistry interface from @aurelia/web-components and register your web components:
import{Aurelia,AppTask}from'aurelia';import{IWcElementRegistry}from'@aurelia/web-components';Aurelia.register(AppTask.creating(IWcElementRegistry,registry=>{ // Define your web components hereregistry.define('my-element',classMyElement{static template ='<p>Hello from Web Component!</p>';});}) ).app(classApp{}).start();
API Reference
The IWcElementRegistry.define method has the following signatures:
Parameters
name: The custom element name (must contain a hyphen - as per Web Components specification)
def: Either a class constructor or an object with element definition properties
options: Optional configuration for extending built-in elements
How it works
Each web component custom element is backed by an Aurelia view model, like a normal Aurelia component.
For each define call, a corresponding native custom element class is created and registered with the browser's customElements registry.
Each bindable property on the backing Aurelia view model is converted to a reactive attribute (via observedAttributes) and reactive property on the custom element.
The web component uses standard Web Components lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback, adoptedCallback).
Regular custom elements: Used as <my-element></my-element> in HTML.
Extended built-in elements: Used as <button is="my-button"></button> in HTML with the is attribute.
Important Notes
Web component custom elements work independently of Aurelia components. The same class can be both a web component and an Aurelia component, though this should be avoided to prevent double rendering.
containerless mode is not supported. Use extend-built-in functionality instead if you want to avoid wrapper elements.
Defined web components continue working even after the owning Aurelia application has stopped.
template and bindables information is retrieved and compiled only once per define call. Changes after this call have no effect.
Slot: [au-slot] is not supported when upgrading existing elements. Standard <slot> elements work as normal web components.
Examples
For simplicity, all examples below define elements at application start, but they can be defined at any time after the container is available.
1. Basic Web Component
2. Web Component with Bindable Properties
3. Web Component with Shadow DOM
4. Web Component with Lifecycle and Host Injection
5. Web Component with Object Definition
6. Extending Built-in Elements
When extending built-in elements, you use the { extends: 'element-name' } option and reference them in HTML using the is attribute:
7. Web Component with Advanced Features
Error Handling and Validation
The web components implementation includes built-in validation:
Invalid Element Names
Containerless Components
Usage Outside Aurelia Applications
Web components defined with Aurelia can be used in any context:
Vanilla JavaScript
React Integration
Angular Integration
Best Practices
Element Naming: Always use kebab-case with at least one hyphen for element names.
Property Binding: Define bindable properties explicitly using the bindables array for reactive updates.
Shadow DOM: Use Shadow DOM for style encapsulation when your component has its own styles.
Lifecycle Management: Implement attaching and detaching lifecycle methods for setup and cleanup.
Error Handling: Always handle errors gracefully, especially in async operations.
Performance: Remember that web components are created for each instance, so avoid heavy operations in constructors.
Dependencies: Keep dependencies minimal since web components should be self-contained.
Extended Built-ins: When extending built-in elements, remember to use the is attribute in HTML (<button is="my-button">) rather than creating new element names.
This enhanced documentation provides a complete guide to creating and using Aurelia-powered Web Components with accurate examples and proper error handling.
// This will throw an error because element names must contain a hyphen
registry.define('myelement', class MyElement {}); // ❌ Error!
// This works
registry.define('my-element', class MyElement {}); // ✅ Correct!
// This will throw an error because containerless is not supported
registry.define('my-element', class MyElement {
static containerless = true; // ❌ Error!
});
// Use extend-built-in instead if you need to avoid wrapper elements
registry.define('enhanced-span', class MyElement {
static template = '<span>Content</span>';
}, { extends: 'span' }); // ✅ Alternative approach
// Usage in HTML: <span is="enhanced-span">Content</span>
<!DOCTYPE html>
<html>
<head>
<script src="./aurelia-web-components-bundle.js"></script>
</head>
<body>
<!-- Use regular web components -->
<user-greeting name="John" age="25"></user-greeting>
<!-- Use extended built-in elements -->
<button is="enhanced-button" variant="primary">Click Me</button>
<script>
// Create regular web components programmatically
const greeting = document.createElement('user-greeting');
greeting.name = 'Jane';
greeting.age = 30;
document.body.appendChild(greeting);
// Create extended built-in elements programmatically
const enhancedBtn = document.createElement('button', { is: 'enhanced-button' });
enhancedBtn.variant = 'secondary';
enhancedBtn.textContent = 'Dynamic Button';
document.body.appendChild(enhancedBtn);
</script>
</body>
</html>
import React from 'react';
function App() {
return (
<div>
<h1>React App with Aurelia Web Components</h1>
<user-greeting name="React User" age="25" />
{/* For extended built-in elements: */}
<button is="enhanced-button" variant="primary">Enhanced Button</button>
</div>
);
}
// app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
@NgModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }