4

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?

Keith
  • 150,284
  • 78
  • 298
  • 434

1 Answers1

8

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>
Keith
  • 150,284
  • 78
  • 298
  • 434
Shirin Safaeian
  • 950
  • 6
  • 18
  • Cheers, that works (+1 and ans). Any idea why it is required? Surely without a default an unspecified title is `undefined`, which is still falsey. – Keith Jan 13 '17 at 12:17
  • 2
    Polymer doesn't render expressions with not-yet-set variables. Computed properties also work this way. [Read more](https://www.polymer-project.org/1.0/docs/devguide/observers#simple-observers). – alesc Jan 14 '17 at 13:47