SoFunction
Updated on 2025-04-03

Instructions for using dom-if and is attributes in JS framework Polymer

We often think of template rendering needs based on the value of a certain attribute, that is, the most basic branch statement. There is ng-if in Angular, so of course there is dom-if in Polymer. In fact, dom-if is a very simple thing. It is just an access point for this topic. What I want to introduce is actually the property.
dom-if, like the dom-repeat mentioned before, is used on the tempalte element through the is attribute. For example, the following example is that two templates determine who should be rendered based on the boolean value on a binding control.
run

<script> var Polymer = { dom: 'shadow' }; </script>
<base href="/share/" />
<link rel="import" href="polymer/" />

<dom-module >
 <template>
  <input type="checkbox" checked="{{checked::change}}">
  <template is="dom-if" if="[[checked]]">true</template>
  <template is="dom-if" if="[[!checked]]">false</template>
 </template>
 <script>
  Polymer({
   properties: {
    checked: { value: false }
   },
   is: 'demo-test'
  });
 </script>
</dom-module>

<demo-test></demo-test>

Whether it is dom-if or the previous dom-repeat, what exactly are these is attributes specified? In fact, it is the same as Angular. They are both Directive concepts, but Polymer does not call it Directive. We can create something like this by ourselves, for example, in the following example, we add an is="demo-test" thing to the div element
run

&lt;script&gt; var Polymer = { dom: 'shadow' }; &lt;/script&gt;
&lt;base href="/share/" /&gt;
&lt;link rel="import" href="polymer/" /&gt;

&lt;script&gt;
 Polymer({
  is: 'demo-test',
  extends: 'div', &lt;!-- Here's the key
  ready: function(e) {
    = 'I'm a demo-test';
  }
 });
&lt;/script&gt;

&lt;div is="demo-test"&gt;&lt;/div&gt;

When defining, you can get an is directive by specifying a tag name through extends. The above example is the easiest way to use it. We can create Shadow DOM ourselves and do what we want to do. In fact, the built-in dom-repeat and dom-if of Polymer are also defined in this way. But this thing looks very complicated in detail, and my article is just an entry-level thing. If you want to know more specific usage, you should look at the source code (I haven't even found where to define the official documentation).