Is it possible to alter the styling (using 'style' or 'css' binding) of a select list's option element when using the 'options' binding on a select list? Or can this only be done by using a 'foreach' on the select list and altering the styling for each ?
I have this in code:
<select id="components-select" size="4" name="components-select"
data-bind=" options: combinedComponents,
optionsText: 'displayName',
optionsValue: 'id',
value: chosenComponent"></select>
but if I append style: {color: isDefault() === true ? 'black' : 'red'}
then the entire list is coloured Red if isDefault
returns false.
Is the only way to achieve this to code it this way:
<select id="components-select" size="4" name="components-select"
data-bind="foreach: combinedComponents">
<option data-bind="value: id, text: displayName, style: {color: isDefault() === true ? 'black' : 'red'}"></option>
</select>
Or is there some form of Knockout.js wizardry that I am not aware of?
Thanks!
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
If you want to add "class" as the name of one, put between apostrophes like 'class' .
To expand on Thomas Wiersema's answer, the way you'd want to approach handling that on a per-row basis is something like:
<select id="components-select" size="4" name="components-select"
data-bind="foreach: combinedComponents">
<option data-bind="value: id, text: displayName, style: {color: getColorFor.call(null, $data) }"></option>
</select>
then, in JavaScript, attach a function to your parent object like so (I'm making some assumptions, of course, like your parent object being called vm
and isDefault
belonging to a combinedComponent):
vm.getColorFor = function(component) {
return component.isDefault() === true ? 'black' : 'red';
}
If you're not sure what call
does, check out bind vs apply vs call
I hope that helps -- let me know if I can elaborate!
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