javascriptcsslit-element

LitElement - Don't add attribute if value is false


Is there a way to basically render these three possibilities:

<my-el someValue="a"></my-el>
<my-el someValue="b"></my-el>
<my-el></my-el> 

Note the explicit lack of the attribute someValue on the third.

To render this normally I would do:

render() {
  const someValue = "a";

  return html`
    <my-el someValue=${someValue}></my-el>
  `;
}

But if someValue was undefined, it would render as <my-el someValue="undefined"></my-el> which I don't want.

Is there a way to get boolean-like behavior for falsy, but show the value for truthy values? I read the docs, but hopefully I'm missing something.

The reason I want to do this is because I'd like to have a CSS selector that affects all of them that have [someValue] regardless of what the actual value is, but to not apply that if it isn't there.

P.S., I'm aware of workarounds like using :not([someValue=undefined]) or returning conditional HTML, so please don't reply with those. I'm using one of those right now, but if there is a direct answer to my question, hoping to swap out for that for a little cleaner code. Thanks.


Solution

  • You can simply use ifDefined directive for this. For AttributeParts, it sets the attribute if the someValue is defined and removes the attribute if the someValue is undefined. You can then further modify it using ternary operator to check for falsy values as well:

    import {ifDefined} from 'lit-html/directives/if-defined';
    
    return html`
       <my-el someValue=${ifDefined(someValue ? someValue : undefined)}></my-el>
    `;