Anyone know if I can have an html element with both a static class name as well as a dynamic, data-bound class name using KnockoutJS? Something like this:
<span class='staticClassName {{viewModelPropertyValue}}'></span>
I realize this isn't ko syntax, I'm just using this syntax to get the point across.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
The "data-bind" attribute contains a collection of comma-separated options for how Knockout should bind a view model property to an HTML element. The two examples above use only a single option: the "value" binding handler.
You can use the css
binding to add and remove a class based on the truthiness of a value, but it sounds like your viewModelProperty is the name of a class rather than a boolean.
You can use the attr
binding with the static class included like: (attr: { 'class': 'staticClassName ' + viewModelPropertyValue }
or (viewModelPropertyValue()
if it is an observable).
Otherwise, there is a community binding here that will add and remove a class in the manner that you are after: https://github.com/SteveSanderson/knockout/wiki/Bindings---class
In Knockout 2.2.0, you can!
<span class='staticClassName' data-bind='css: viewModelPropertyValue'></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With