I want to add a class behind payment-method
by function with the knockout css binding (in Magento 2.1).
So this is the current code:
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio"
name="payment[method]"
class="radio"
data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>
The class is returned by getCode()
which works above with the id and value.
So I thought I could do just:
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked()), getCode()}">
But then it fails with:
knockout.js:2624 Uncaught SyntaxError: Unable to parse bindings.
Bindings value: css: {‘_active’: (getCode() == isChecked()), getCode() }
Message: Unexpected token }
<div class="payment-method" data-bind="css: getCode()">
This works.
<div class="payment-method" data-bind="css: {getCode()}">
This doesn’t.
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}, attr: {'class': getCode()}">
This works too but will overwrite the payment-method
class and the _active
class isn’t set either initally anymore.
How do I set that dynamic class?
3
Answers
The comment from @tyler_mitchell helped me find the solution myself through this thread: https://stackoverflow.com/a/21528681/928666
I can do:
Not brilliant but well...
This piece of code is redundant, as the css data-bind is getting overwrite with your attr binding.
This is how you can do your dynamic class (assumption these properties are observable):
Another example should anyone need it