Search code examples
lit-html

Using a condition for having attributes in a paper-input


I'm using lit-html with a paper-input which is a polymer 3 element. I would like to make a condition where some attributes are put in the paper-input-attributes by a condition.

Note this does not seem to be related to paper-input. Different error occurs using simple input

render(){
    return html`
                                             <!--Using placeholder or value depending on a condition-->
        <paper-input label="Video title" type="text"
            id="titleInput" name="title" ${((true) ? html`placeholder="${this.videotitle}" `: html`value="${this.videotitle}" `)}>
        </paper-input>
`;}

I'm expecting to have either the placeholder or the value set based on the condition.

/*Error message from console*/
Uncaught (in promise) TypeError: Cannot read property '2' of null
    at _prepareTemplate (template.ts:102)
    at new Template (template.ts:203)
    at Object.templateFactory (shady-render.ts:94)
    at NodePart._commitTemplateResult (parts.ts:285)
    at NodePart.commit (parts.ts:230)
    at render (render.ts:57)
    at Function.render (shady-render.ts:284)
    at HTMLElement.update (lit-element.ts:231)
    at HTMLElement.performUpdate (updating-element.ts:772)
    at HTMLElement._enqueueUpdate (updating-element.ts:717)

When using a input field like below:

<input 
${((true) ? html`placeholder="${this.videotitle}" `: html`value="${this.videotitle}"`)} >
</input>

the DOM is like this: DOM and looks like this: rendered result

I found these relevant rules in the documentation which I believe I am following:

  • Bindings can only occur in attribute-value and text-content positions.

  • Templates should not contain unclosed elements—they will be closed by the HTML parser. Reference: https://lit-html.polymer-project.org

I'm not successful in doing it that way. Anybody know of the way? I can of course just separate them, but I would like a neat way.


Solution

  • As the documentation says:

    Bindings can only occur in attribute-value and text-content positions.

    That is:

    <element attribute="${/* Here */}">
      ${/* Or here */}
    </element>
    

    Try setting each attribute value according to the condition:

    <paper-input placeholder=${condition ? this.videotitle : null}
                 value=${condition ? null : this.videotitle}>
    </paper-input>