Home

Awesome

Build Status npm version

Ember Custom Elements

The most flexible way to render parts of your Ember application using custom elements!

Demos

Table of Contents

Compatibility

This add-on won't work at all with versions of ember-source prior to 3.6.0. I will not be actively trying to support versions of Ember that are not recent LTS versions, but I'm open to any pull requests that improve backward compatibility.

Installation

ember install ember-custom-elements

If you are targeting older browsers, you may want to use a polyfill for custom elements. Other features of web components are also available as polyfills.

Usage

Components

All you have to do is use the customElement decorator in your component file:

import Component from '@glimmer/component';
import { customElement } from 'ember-custom-elements';

@customElement('my-component')
export default MyComponent extends Component {

}

Now you can use your component anywhere inside the window that your app was instantiated within by using your custom element:

<my-component></my-component>

In the case that you can't use TC39's proposed decorator syntax, you can call customElement as a function and pass the target class as the first argument:

export default customElement(MyComponent, 'my-component');

However, it's recommended that you upgrade to a recent version of ember-cli-babel so you can use decorator syntax out of the box, or manually install babel-plugin-proposal-decorators.

In newer versions of Ember, you will get a linting error if you have an empty backing class for your component. Since the @customElement decorator needs to be used in a JS file in order to implement a custom element for your component, you may have no choice but to have an empty backing class.

Thus, you may want to disable the ember/no-empty-glimmer-component-classes ESLint rule in your Ember project. In the future, we will explore ways to define custom elements for tagless components, but until then you either need a component class defined.

Attributes and Arguments

Attributes instances of your custom element are translated to arguments to your component:

<my-component some-message="hello world"></my-component>

To use the attribute in your component template, you would use it like any other argument:

{{!-- my-component.hbs --}}
{{@some-message}}

Changes to attributes are observed, and so argument values are updated automatically.

Block Content

Block content inside your custom element instances can be treated just like block content within a precompiled template. If your component contains a {{yield}} statement, that's where the block content will end up.

{{!-- my-component.hbs --}}
<span>foo {{yield}} baz</span>
<my-component>bar</my-component>

When the component is rendered, we get this:

<span>foo bar baz</span>

Block content can be dynamic. However, the consuming element needs to be able to handle its children being changed by other forces outside of it; if a child that's dynamic gets removed by the custom element itself, that can lead to the renderer getting confused and spitting out errors during runtime.

You can see dynamic block content can work in this demo.

Routes

The @customElement decorator can define a custom element that renders an active route, much like the {{outlet}} helper does. In fact, this is achieved by creating an outlet view that renders the main outlet for the route.

Just like with components, you can use it directly on your route class:

/* app/routes/posts.js */

import Route from '@ember/routing/route';
import { customElement } from 'ember-custom-elements';

@customElement('test-route')
export default class PostsRoute extends Route {
  model() {
    ...
  }
}

In this case, the <test-route> element will render your route when it has been entered in your application.

Named Outlets

If your route renders to named outlets, you can define custom elements for each outlet with the outletName option:

/* app/routes/posts.js */

import Route from '@ember/routing/route';
import { customElement } from 'ember-custom-elements';

@customElement('test-route')
@customElement('test-route-sidebar', { outletName: 'sidebar' })
export default class PostsRoute extends Route {
  model() {
    ...
  }

  renderTemplate() {
    this.render();
    this.render('posts/sidebar', {
      outlet: 'sidebar'
    });
  }
}

In this example, the <test-route-sidebar> element exhibits the same behavior as {{outlet "sidebar"}} would inside the parent route of the posts route. Notice that the outletName option reflects the name of the outlet specified in the call to the render() method.

Note that the use of renderTemplate is being deprecated in newer versions of Ember.

Outlet Element

This add-on comes with a primitive custom element called <ember-outlet> which can allow you to dynamically render outlets, but with a few differences from the {{outlet}} helper due to technical limitations from rendering outside of a route hierarchy.

Usage

The outlet element will not be defined by default. You must do this with the @customElement decorator function. Here is an example of an instance-initializer you can add to your application that will set up the outlet element:

// app/custom-elements.js

import { setOwner } from '@ember/application';
import { customElement, EmberOutletElement } from 'ember-custom-elements';

@customElement('ember-outlet')
export default class OutletElement extends EmberOutletElement {

}

This will allow you to render an outlet like this:

<ember-outlet></ember-outlet>

By default, the <ember-outlet> will render the main outlet for the application route. This can be useful for rendering an already initialized Ember app within other contexts.

To render another route, you must specify it using the route= attribute:

<ember-outlet route="posts.index"></ember-outlet>

If your route specifies named routes, you can also specify route names:

<ember-outlet route="posts.index" name="sidebar"></ember-outlet>
<ember-outlet route="posts.index" name="content"></ember-outlet>

Since an <ember-outlet> can be used outside of an Ember route, the route attribute is required except if you want to render the application route. You cannot just provide the name= attribute and expect it to work.

In the unusual circumstance where you would be loading two or more Ember apps that use the ember-outlet element on the same page, you can extend your own custom element off the ember-outlet in order to resolve the naming conflict between the two apps.

Applications

You can use the same @customElement decorator on your Ember application. This will allow an entire Ember app to be instantiated and rendered within a custom element as soon as that element is connected to a DOM.

Presumably, you will only want your Ember app to be instantiated by your custom element, so you should define autoboot = false; in when defining your app class, like so:

/* app/app.js */

import Application from '@ember/application';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
import { customElement } from 'ember-custom-elements';

@customElement('ember-app')
export default class App extends Application {
  modulePrefix = config.modulePrefix;
  podModulePrefix = config.podModulePrefix;
  Resolver = Resolver;
  autoboot = false;
  // 👆 this part is important
}

loadInitializers(App, config.modulePrefix);

Once your app has been created, every creation of a custom element for it will only create new application instances, meaning that your instance-initializers will run again but your initializers won't perform again. Custom elements for your app are tied directly to your existing app.

Native Custom Elements

The customElement decorator can also be used on native custom elements (i.e. extensions of HTMLElement).

/* app/custom-elements/my-element.js */
import { customElement } from 'ember-custom-elements';

@customElement('my-element')
export default class MyElement extends HTMLElement {

}

There's a few minor things that this add-on does for you when it comes to using plain custom elements:

It's important that your custom elements are located in a folder named app/custom-elements so that they can be properly registered with your application. This add-on will NOT infer the tagName of the elements from their respective file names; you must always use the @customElement decorator.

Options

At present, there are a few options you can pass when creating custom elements:

Options Example

@customElement('my-component', { extends: 'p', useShadowRoot: true })
export default MyComponent extends Component {

}

Global Default Options

In the case where you want to apply an option to all uses of the customElement decorator, you can set the option as a global default in the config/environment.js of your Ember project.

For example, if you want preserveOutletContent to be applied to all route elements, you can add this option to ENV.emberCustomElements.defaultOptions:

module.exports = function(environment) {
  ...
  emberCustomElements: {
    defaultOptions: {
      preserveOutletContent: true
    }
  },
  ...
}

Accessing a Custom Element

The custom element node that's invoking a component can be accessed using the getCustomElement function.

Simply pass the context of a component; if the component was invoked with a custom element, the node will be returned:

import Component from '@glimmer/component';
import { customElement, getCustomElement } from 'ember-custom-elements';

@customElement('foo-bar')
export default class FooBar extends Component {
  constructor() {
    super(...arguments);
    const element = getCustomElement(this);
    // Do something with your element
    this.foo = element.getAttribute('foo');
  }
}

Forwarding Component Properties

HTML attributes can only be strings which, while they work well enough for many purposes, can be limiting.

If you need to share state between your component and the outside world, you can create an interface to your custom element using the forwarded decorator. Properties and methods upon which the decorator is used will become accessible on the custom element node. If an outside force sets one of these properties on a custom element, the value will be set on the component. Likewise, a forwarded method that's called on a custom element will be called with the context of the component.

import Component from '@glimmer/component';
import { customElement, forwarded } from 'ember-custom-elements';

@customElement('foo-bar')
export default class FooBar extends Component {
  @forwarded
  bar = 'foobar';

  @forwarded
  fooBar() {
    return this.bar.toUpperCase();
  }
}

When rendered, you can do this:

const element = document.querySelector('foo-bar');
element.bar; // 'foobar'
element.fooBar(); // 'FOOBAR"

If you are using tracked from @glimmer/tracking, you can use it in tandem with the forwarded decorator on properties.

Notes

Elements

Once a custom element is defined using window.customElements.define, it cannot be redefined.

This add-on works around that issue by reusing the same custom element class and changing the configuration associated with it. It's necessary in order for application and integration tests to work without encountering errors. This behavior will only be applied to custom elements defined using this add-on. If you try to define an application component on a custom element defined outside of this add-on, an error will be thrown.

Runloop

Because element attributes must be observed, the argument updates to your components occur asynchronously. Thus, if you are changing your custom element attributes dynamically, your tests will need to use await settled().

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.