Search code examples
javascriptlit

Why are conditional events in Lit not working?


The following code renders with no event handlers attached. I've verified that this.evchange and/or this.evinput are true. The events work if I set them up more verbosely. But from reading the Conditionals section in the docs, this should work.

let evc = (this.evchange) ? html`@change=${this._changed}` : '';

let evi = (this.evinput) ? html`@input=${this._changed}` : '';

return html`${this.flabel} <input .value=${this.fvalue} ${evc} ${evi}>`;


Solution

  • Each html tag function needs to contain well-formed HTML. So it is not valid for the template to just contain an event binding.

    To conditionally add event binding, you should should add the conditional within the expression and return nothing for falsy cases like:

    import {nothing} from 'lit';
    
    return html`
      <input
        .value =${this.fvalue}
        @change=${this.evchange ? this._changed : nothing}
        @input=${this.evinput ? this._changed : nothing}
      >
    `;