Search code examples
typescriptlit

Pass a boolean value to a Lit Component


I want to pass a boolean value (true/false) to a lit component via. the dom. I'm having issues because it is always converted to true, I cant seem to find a good example for this in the lit documentation.

So basically:

<my-element foo="false" />
...
  @property({type: Boolean})
  foo: boolean;

What I tried allready is try to pass: "${false}"

I created a lit playground link with an example here


Solution

  • In HTML, boolean attributes are dictated by whether they are present or not, not by the string value.

    You should simply omit the attribute:

    <my-element></my-element>
    

    And default the property to false:

    class MyElement extends LitElement {
      @property({type: Boolean})
      foo: boolean = false;
    }
    

    If you're writing markup within lit-html templates, you can use the boolean attribute expression.

    let foo = false;
    html`<my-element ?foo=${foo}></my-element>`;