15

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?

Jorge Hernandez
  • 187
  • 1
  • 1
  • 10

3 Answers3

18

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

AlexO
  • 1,311
  • 12
  • 18
  • 2
    What does the `$= ` do? I didn't see it explained anywhere. It appears I need it for this scenario, though other places where I've seen it used ` simple `=` suffices. – Guss Mar 28 '16 at 13:51
  • 1
    the `$=` is used when binding to attributes (such as: class, style, href, etc.), as opposed to properties: https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#attribute-binding – AlexO Mar 28 '16 at 20:00
13

update Polymer 1.0

<div class$="[[getClasses(item.completed)]]">
getClasses: function (completed) {
  var classes = 'bottom'
  if(completed) classes += ' completed';
  return classes;
}

Even when completed could be read from this.item.completed inside getClasses() it's important to pass it as parameter from the binding. This way Polymer re-evaluates the function getClasses(item.completed) each time item.completed changed.

original - Polymer 0.5

It should look like

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

See docs for more details: http://polymer-project.org/docs/polymer/expressions.html#tokenlist

Freek Wiekmeijer
  • 4,556
  • 30
  • 37
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

the simplest way to do it:

<template>
  <style is="custom-style">
      .item-completed-true { background: red; }
  </style>
  <div class$="bottom item-completed-[[item.completed]]"></div>
</template>
Adriano Spadoni
  • 4,540
  • 1
  • 25
  • 25