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

2
  • Not familiar with hyperHTML, but it seems you are missing a "=" in `this.html = <custom-element myboolean=${this.flag}></custom-element>; What does not work? Commented Aug 30, 2018 at 5: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". Commented Aug 30, 2018 at 5:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.