2

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"?

  • Not familiar with hyperHTML, but it seems you are missing a "=" in `this.html = ````; What does not work? – faerin Aug 30 '18 at 05:05
  • `this.html` is a hyperHTML function that accepts a template literal. The issue is that for certain attributes already defined, e.g. `disabled`, it will properly render the attribute. For `myboolean`, it will render as `myboolean="false"`. – Spicy Meatball Aug 30 '18 at 05:11

1 Answers1

1

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.

Andrea Giammarchi
  • 3,038
  • 15
  • 25