polymerdom-if

Polymer dom-if: how do I implement a negative condition?


I have a Polymer element that uses <template is="dom-if"... to provide different HTML content depending on a condition.

Polymer dom-if has no else condition, so needs a negative if condition to simulate it.

Something like this:

<link href="https://polygit.org/components/polymer/polymer.html" rel="import">

<dom-module id="test-thing">
  <template>
    <template is="dom-if" if="{{title}}" restamp>
      <b>[[title]]</b>
    </template>
    <template is="dom-if" if="{{!title}}" restamp>
      <i>no title</i>
    </template>
  </template>
  <script>
    Polymer({
      is: 'test-thing',
      properties: {
        title: String
      }
    });
  </script>
</dom-module>

<div>
  With negative condition:
  <test-thing></test-thing>
</div>
<div>
  With positive condition:
  <test-thing title="Has Title"></test-thing>
</div>

Only that doesn't work - the negative condition never passes.

How should this be implemented?


Solution

  • You must use a default empty value for your title property:

      title:{type: String,value:''}
    

    Like so:

    <link href="https://polygit.org/components/polymer/polymer.html" rel="import">
    
    <dom-module id="test-thing">
      <template>
        <template is="dom-if" if="{{title}}" restamp>
          <b>[[title]]</b>
        </template>
        <template is="dom-if" if="{{!title}}" restamp>
          <i>no title</i>
        </template>
      </template>
      <script>
        Polymer({
          is: 'test-thing',
          properties: {
            title: {type: String,value:''}
          }
        });
      </script>
    </dom-module>
    
    <div>
      With negative condition:
      <test-thing></test-thing>
    </div>
    <div>
      With positive condition:
      <test-thing title="Has Title"></test-thing>
    </div>