Search code examples
javascripthyperhtml

hyperHTML: Custom Boolean Attributes


Is it possible to have a custom boolean attribute? In the hyperHTML documentation for Boolean Attributes, it states the following:

Just use boolean attributes any time you need them, if it's part of the element's inheritance, it'll always do the right thing.

This snippet doesn't work:

this.html`<custom-element myboolean=${this.flag}></custom-element>`;

If I needed custom to be a boolean attribute, how could I make it so that it's "part of the element's inheritance"?


Solution

  • In order to have the attribute part of the inheritance you need to define it as such.

    With custom elements, simply defining an attribute as observable wouldn't make it an inherited attribute, you need explicitly configure it as such.

    Example

    customElements.define(
      'custom-element',
      class CustomElement extends HTMLElement {
        static get observedAttributes() {
          return ['myboolean'];
        }
        get myboolean() {
          return this.hasAttribute('myboolean');
        }
        set myboolean(value) {
          if (value) this.setAttribute('myboolean', true);
          else this.removeAttribute('myboolean');
        }
      }
    );
    

    Once you have such definition in place, you'll see that everything works as expected, as shown in this Code Pen.

    hyperHTML(document.body)`
      <custom-element myboolean=${false}>
        Boolean test
      </custom-element>
    `;
    

    Alternatively, you can define your Custom Elements via HyperHTMLElement booleanAttributes to simplify that boilerplate for boolean attributes.