LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Introduction
  • Installing The Plugin
  • How it works
  • Examples

Was this helpful?

Export as PDF
  1. Developer Guides

Web Components

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 in Web Components.

Installing The Plugin

The web components package needs to be installed:

npm install @aurelia/web-components

To use the plugin, import the interface IWcElementRegistry interface from @aurelia/web-components 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.

How it works

  • 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.

Examples

For simplicity, all the examples below define elements at the start of an application, but they can be defined at any time.

  1. Defining a tick-clock element

import { Aurelia } from 'aurelia';
import { IWcElementRegistry } from "@aurelia/web-components";

Aurelia
  .register(
    AppTask.creating(IWcElementRegistry, registry => {
      registry.define('tick-clock', class TickClock {
        static template = '${message}';

        constructor() {
          this.time = Date.now();
        }

        attaching() {
          this.intervalId = setInterval(() => {
            this.message = `${Date.now() - this.time} seconds passed.`;
          }, 1000)
        }

        detaching() {
          clearInterval(this.intervalId);
        }
      })
    })
  )
  .app(class App {})
  .start();
  1. Defining a tick-clock element using shadow DOM with open mode

import { Aurelia } from 'aurelia';
import { IWcElementRegistry } from "@aurelia/web-components";

Aurelia
  .register(
    AppTask.creating(IWcElementRegistry, registry => {
      registry.define('tick-clock', class TickClock {
        static template = '${message}';
        static shadowOptions = { mode: 'open' };

        constructor() {
          this.time = Date.now();
        }

        attaching() {
          this.intervalId = setInterval(() => {
            this.message = `${Date.now() - this.time} seconds passed.`;
          }, 1000)
        }

        detaching() {
          clearInterval(this.intervalId);
        }
      })
    })
  )
  .app(class App {})
  .start();
  1. Injecting the host element into the view model

import { INode, Aurelia } from 'aurelia';
import { IWcElementRegistry } from "@aurelia/web-components";

Aurelia
  .register(
    AppTask.creating(IWcElementRegistry, registry => {
      registry.define('tick-clock', class TickClock {
        static template = '${message}';
        static shadowOptions = { mode: 'open' };

        // all these injections result in the same instance
        // listing them all here so that applications can use what they prefer
        // based on HTMLElement 
        static inject = [INode, Element, HTMLElement];

        constructor(node, element, htmlElement) {
          node === element;
          element === htmlElement;
          this.time = Date.now();
        }

        attaching() {
          this.intervalId = setInterval(() => {
            this.message = `${Date.now() - this.time} seconds passed.`;
          }, 1000)
        }

        detaching() {
          clearInterval(this.intervalId);
        }
      })
    })
  )
  .app(class App {})
  .start();
  1. Defining a tick-clock element with format bindable property for formatting

import { INode, Aurelia } from 'aurelia';
import { IWcElementRegistry } from "@aurelia/web-components";

document.body.innerHTML = '<tick-clock format="short"></tick-clock>';

Aurelia
  .register(
    AppTask.creating(IWcElementRegistry, registry => {
      registry.define('tick-clock', class TickClock {
        static template = '${message}';
        static shadowOptions = { mode: 'open' };
        static bindables = ['format'];

        // all these injections result in the same instance
        // listing them all here so that applications can use what they prefer
        // based on HTMLElement 
        static inject = [INode, Element, HTMLElement];

        constructor(node, element, htmlElement) {
          node === element;
          element === htmlElement;
          this.time = Date.now();
        }

        attaching() {
          this.intervalId = setInterval(() => {
            this.message = `${(Date.now() - this.time)/1000} ${this.format === 'short' ? 's' : 'seconds'} passed.`;
          }, 1000)
        }

        detaching() {
          clearInterval(this.intervalId);
        }
      })
    })
  )
  .app(class App {})
  .start();
  1. Defining a tick-clock element extending built-in div element:

import { Aurelia } from 'aurelia';
import { IWcElementRegistry } from "@aurelia/web-components";

document.body.innerHTML = '<div is="tick-clock"></div>'

Aurelia
  .register(
    AppTask.creating(IWcElementRegistry, registry => {
      registry.define('tick-clock', class TickClock {
        static template = '${message}';

        constructor() {
          this.time = Date.now();
        }

        attaching() {
          this.intervalId = setInterval(() => {
            this.message = `${Date.now() - this.time} seconds passed.`;
          }, 1000)
        }

        detaching() {
          clearInterval(this.intervalId);
        }
      })
    }, { extends: 'div' })
  )
  .app(class App {})
  .start();
PreviousBuilding pluginsNextUI virtualization

Last updated 4 months ago

Was this helpful?