lit-elementlit-html

Is there a way to make LitHtml attributes optional?


I'm not talking about boolean attributes, attributes like class if you don't want to add an empty class attribute if there's no CSS class.

html`<span class=${hasClass ? 'my-class' : ''}></span>`

Solution

  • There is an ifDefined directive that does what you want. If the value is undefined the attribute won't be rendered.

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