Pregunta

I want a CSS class to be applied to an element if a certain condition becomes true and that class to be removed when the condition becomes false. This is a pretty common pattern in web programming and I want to know the idiomatic way to do this using Polymer.

¿Fue útil?

Solución

bindCssClass is deprecated (as of Polymer 0.10.0-pre.4)

CSS-classes can now be bound to a Map.

@observable var btnClasses = toObservable({'someclass': true, 'someotherclass': false});

<polymer-element name="spark-button" class="{{btnClasses}}">
  <template>
    ...
</polymer-element>

Otros consejos

This answer is no longer valid. Use the accepted answer instead.

Use bindCSSClass to conditionally bind a CSS class to an element. In the click-counter example below, a 'blue' class is applied to the element that displays the counter value only if the value if divisible by three:

import 'package:polymer/polymer.dart';

@CustomTag('click-counter')
class ClickCounter extends PolymerElement with ObservableMixin {
  @observable int count = 0;

  void increment() {
    count++;
  }

  ClickCounter() {
    bindProperty(this, const Symbol('count'),
        () => notifyProperty(this, const Symbol('divByThree')));
  }

  bool get divByThree => count % 3 == 0;

  void created() {
    super.created();
    var root = getShadowRoot("click-counter");
    var item = root.query('#click-display');
    bindCssClass(item, 'blue', this, 'divByThree');
  }
}

In the example we use a getter to check if the value is divisible by 3:

  bool get divByThree => count % 3 == 0;

Then we create an observable binding for the getter:

  ClickCounter() {
    bindProperty(this, const Symbol('count'),
        () => notifyProperty(this, const Symbol('divByThree')));
  }

Then, within 'created()`, we find the element to which the CSS class is applied (and un-applied):

    var root = getShadowRoot("click-counter");
    var item = root.query('#click-display');

And we use bindCssClass to bind a CSS class to the element based on the divByThree getter returning a boolean value:

    bindCssClass(item, 'blue', this, 'divByThree');

In this case, the 'blue' class is applied to the element when divByThree returns true, and un-applied when it returns false.

bindCssClass is defined in observe package within html.dart.

You can see a full app that uses this code at https://github.com/shailen/dartythings/tree/master/bindCSS.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top