LitElement - How to create dom-if restamp behavior with javascript if expression inside LitElement render method?

891 views Asked by At

We are using "if" expression inside LitElement to selectively render content in render method and would like to re-create child DOM every time "if" expression get re-evaluated(changes). This is something similar to what dom-if element used to support with "restamp" property in polymer 3.

Really appreciate any pointers here to follow?

Thanks, Vishal

2

There are 2 answers

0
Marco Monzón On

Try this:

    render() {
      return html`${
        condition ? html`<p>Hello</p>` : ''
      }`;
    }
0
jorgecasar On

You have 2 options depending on whether the condition will change several times and you want to cache the represented parts or not:

Without cache (vanilla javascript)

render() {
  return html`${
    condition ?
    () => html`Your TRUE HTML here` :
    () => html`Your FALSE HTML here`
  }`;
}

With cache (using cache directive from lit-html)

import { cache } from 'lit-html/directives/cache';
[…]
render() {
  return html`${cache(
    condition ?
    () => html`Your TRUE HTML here` :
    () => html`Your FALSE HTML here`
  )}`;
}