Lit-element: Using lit-element with dom-if

Created on 22 May 2018  路  2Comments  路  Source: Polymer/lit-element

I am sure this is an issue the Polymer team is aware of but I wanted to open this to make sure.

Using dom-if in a lit-element is not working as expected. For instance,

_render(props) {
  return html`
    <dom-if if="${props.shouldRenderThis}">
      <template>
        <mwc-button label="add" on-click="${_ => this.addFunction()}"></mwc-button>
      </template>
    </dom-if>
  `;
}

This will render and visually not broken, but if one clicks on the <mwc-button> the on-click event-listener is not triggered, therefore the addFunction is not called.

And lit-element doesn't really propose a solution, at least not a user-friendly one AFAIK. The work-around I am using right now is something similar to :

_render(props) {

  let addButton = html``;
  if (props.shouldRenderThis) {
    addButton = html`
      <mwc-button label="add" on-click="${_ => this.addFunction()}"></mwc-button>
    `;
  }

  return html`
    ${addButton}
  `;
}

Is there a better solution to create conditional templates in lit-element ? Or is there a working branch already trying to leverage this question ?

Thanks Polymer.

Most helpful comment

Hi @vdegenne

You don't need to use dom-if with LitElement, you can use any javascript construction that pleases your eyes. Such as the example you listed above, or a ternary expression:

_render(props) {
  return html`
        ${props.shouldRenderThis ? html`<mwc-button label="add" on-click="${_ => this.addFunction()}"></mwc-button>` : ''} 
  `;
}

The point is that the function should return a TemplateResult (returned from html``), how you construct it is up to you.

All 2 comments

Hi @vdegenne

You don't need to use dom-if with LitElement, you can use any javascript construction that pleases your eyes. Such as the example you listed above, or a ternary expression:

_render(props) {
  return html`
        ${props.shouldRenderThis ? html`<mwc-button label="add" on-click="${_ => this.addFunction()}"></mwc-button>` : ''} 
  `;
}

The point is that the function should return a TemplateResult (returned from html``), how you construct it is up to you.

Ok now I feel a little bit awkward because I tried the ternary operator before but I was having a false string stamped into my final html but I rewrite the whole thing and now it seems to work good. Thanks for your answer @LarsDenBakker !

Was this page helpful?
0 / 5 - 0 ratings