0

In our lit web-components library we would like to allow users to add web components in the most HTMLwise manner. Is there a way to pass boolean attributes into components like following?

<custom-button disabled> // -> true 
<custom-button> // -> undefined -> (lit) false

Currently it looks like this:

<custom-button disabled="true"

We would like to get rid of boolean assignment and keep just word 'disabled' if it is true, the same as it is done for native HTML elements

badm
  • 219
  • 2
  • 13
  • ``setAttribute("disabled","")`` is standard JS for creating attributes without a value (booleans). https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute If the tool Lit doesn't let you do that, ditch the tool – Danny '365CSI' Engelman Aug 30 '22 at 10:12

1 Answers1

2

When wanting to pass a boolean attribute in lit-html template, you can prefix the attribute with ?.

html`<custom-button ?disabled=${someBoolean}></custom-button>`;

Then Lit will add the attribute based on whether the expression is truthy or falsy. See docs on boolean attributes.

Within the Lit component definition, you can specify a property to be boolean by providing a type

in TypeScript:

class CustomButton extends LitElement {
  @property({type: Boolean})
  disabled = false;
}

in JavaScript:

class CustomButton extends LitElement {
  static properties = {
    disabled = {type: Boolean};
  }

  constructor() {
    super();
    this.disabled = false;
  }
}

such that within the component this.disabled will be a boolean value based on whether the attribute exists or not.

Augustine Kim
  • 841
  • 1
  • 5