javascripttypescriptpolymerpolymer-3.x

Conditional rendering in Polymer 3


I need to render different html based on a bool variables true or false value. For example in react I would do something like this in my return in the render function:

{this.state.booleanValue ? "true" : "false"}

Where I get two different output depending on the value of booleanValue.

I tried in Polymer 3, and first declared my bool variable:

static get properties() {
    return {
      myBoolValue: {
        type: Boolean
      }
    };
  }

I then try to use it in my template/html as

${this.myBoolValue ? "" : ""}

However, the code does not recognize the variable "this.myBoolValue" in the html template. How come? Full code of my template:

static get template() {
    return html`
     
     <div>
        ${this.myBoolValue ? "true" : "false"}  // error, does not recognize "this.myBoolValue". 
   </div>

    `;

Solution

  • If your default value of myBoolValue is false you can change your properties and template like this (If you want to use conditional templates you have to import @polymer/polymer/lib/elements/dom-if.js.)

    static get properties() {
      return {
        myBoolValue: {
          type: Boolean,
          value: false
        }
      };
    }
    static get template() {
      return html`
        <p>[[myBoolValue]]</p>
    
        // OR conditional templates:
        <template is="dom-if" if="{{myBoolValue}}">
          true
        </template>
        <template is="dom-if" if="{{!myBoolValue}}">
          false
        </template>
      `;
    }
    

    If you can't or don't want to set a default value change your code like this and use a computed property:

    static get properties() {
      return {
        myBoolValue: {
          type: Boolean
        },
        computedBool: {
          type: String,
          computed: "_isTrue(myBoolValue)",
          value: false
        }
      };
    }
    
    static get template() {
      return html`
        <p>[[computedBool]]</p>
    
        <template is="dom-if" if="{{computedBool}}">
          true
        </template>
        <template is="dom-if" if="{{!computedBool}}">
          false
        </template>
      `;
    }
    
    _isTrue(a) {
      return a === true;
    }