2

I have seen this in angular before and wondered if this is possible in polymer as well. Angular - What is the best way to conditionally apply a class?

I have set up a property named 'animated':

animated: {
  type: Boolean,
  value: false,
},

When animated is true, a div inside my element should have a css class of .animate.

<div class=""></div>

For now I have done that inside of the ready function. But since I came across that Stackoverflow question I wondered if this is prossible in polymer.

Thanks!

Community
  • 1
  • 1
André Kuhlmann
  • 4,378
  • 3
  • 23
  • 42

2 Answers2

5

One way to do that is using a function as follow:

<div class$="{{_getClass(animated)}}"></div>

Where class$ with $ symbol indicates to Polymer's that property is generate using data binding. So, your _getClass function will look like this:

_getClass: function(animated){
   return animated ? "animate" : "";
}

When animate property changes, the _getClass function will be invoked and this function will return the string that indicates the class you need.

Flavio Ochoa
  • 961
  • 7
  • 20
2

You can also use toggleClass method of Polymer

<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<dom-module id="my-element">
  <template>
    <style>
      .show {
        display: block !important;
        border: 1px solid black;
      }
      .hide {
        width: 100px;
        height: 100px;
        display: none;
      }
    </style>
    <div class="hide" id="toggle"></div>
    <button on-tap="_toggleDiv">Press to toggle</button>
  </template>
</dom-module>
<script>
  Polymer({
    is: 'my-element',
    properties: {
      show: {
        type: Boolean,
        value: false
      }
    },
    _toggleDiv: function() {
      this.show = !this.show;
      this.toggleClass('show', this.show, this.$.toggle);
    }
  });
</script>

<my-element></my-element>
a1626
  • 2,953
  • 1
  • 19
  • 34