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.