Conditionally add css class in polymer

Jorge Hernandez picture Jorge Hernandez · Dec 1, 2014 · Viewed 14.6k times · Source

I have an element inside a polymer component and want to add a css class conditionally.

<div class="bottom {{completed: item.completed}}">

if item.isCompleted is true, then add the .completed class.

However, I've got the following error:

Invalid expression syntax: completed?: item.completed

I don't want to put the hole subtree inside a template conditional. Is it possible to do using an expression inside an html tag? I'm using the last polymer release, is this funtionallity migrated or replaced in any way?

Answer

AlexO picture AlexO · Jan 3, 2016

The tokenlist technique was valid in Polymer 0.5, but has been deprecated.

As of Polymer 1.2, the following works:

<dom-module ...>
  <template>
    <div class$="bottom [[conditionalClass(item.completed)]]"></div>
  </template>
  <script>
    Polymer({
      ...
      conditionalClass: function(completed) {
        return completed ? 'completed' : '';
      }
    });
  <script>
</dom-module>

Also see similar question: Polymer 1.0 - Binding css classes