Week 20 | Conditional Templates

polymer 1.0
Thu Jan 12 2017

Polymer provides a set of custom elements to help with common data binding use cases. Let us check the conditional templates. We have the custom HTMLTemplateElement type extension called dom-if. With this we can stamp contents to the DOM only when the property in it is set to true.

In our example, the isSecureMessage will create and add the content in the template when it is set to true. I’ll go to the ready method and set the property to true and set it to false after 3 seconds. This will create and append our super secure message and after 3 seconds will destroy the DOM item because it sets it to false again.

<!DOCTYPE html>
<html>
<head>
  <script src="https://polygit.org/polymer+:1.3.1/components/webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="https://polygit.org/polymer+:1.3.1/components/polymer/polymer.html" />
</head>
<body>
  <alert-element></alert-element>
  <dom-module id="alert-element">
    <template>
      Secure Messages:
      <br/>
      <template is="dom-if" if="{{isSecureMessage}}">
        Super Secure! <span>{{message}}</span>
      </template>
    </template>
  </dom-module>
  <script>
    HTMLImports.whenReady(function() {
      Polymer({
        is: "alert-element",
        properties: {
          message: {
            type: String,
            value: "This message is super secure. It will self-destruct."
          },
          isSecureMessage: {
            type: Boolean,
            value: false
          }
        },
        ready: function() {
          var self = this;
          self.isSecureMessage = true;
          setTimeout(function(){
              self.isSecureMessage = false;
          }, 3000);
        }
      });
    });
  </script>
</body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!