Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add css class in polymer

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?

like image 337
Jorge Hernandez Avatar asked Dec 01 '14 12:12

Jorge Hernandez


People also ask

Can CSS add a class to an element?

CSS classes can be added to any HTML element.

How do you add CSS to a class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

What are conditional classes?

Conditional Class property allows you to bind an expression which will be evaluated and appended as classes to a widget. Conditional Class property can be set for the following Widgets: Label.


3 Answers

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

like image 94
AlexO Avatar answered Oct 11 '22 00:10

AlexO


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

like image 39
Günter Zöchbauer Avatar answered Oct 10 '22 22:10

Günter Zöchbauer


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>
like image 41
Adriano Spadoni Avatar answered Oct 11 '22 00:10

Adriano Spadoni