Reputation: 1924
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?
Upvotes: 1
Views: 2941
Reputation: 25284
Another example should anyone need it
<div data-bind="attr: { 'class': 'mainClass' + (dynamicClassSetOnce ? ' ' + dynamicClassSetOnce : '' }, css: { 'mainClass--focussed': isFocussed }">
...
</div>
Upvotes: 0
Reputation: 1924
The comment from @tyler_mitchell helped me find the solution myself through this thread: https://stackoverflow.com/a/21528681/928666
I can do:
<div class="payment-method" data-bind="attr: { 'class': 'payment-method ' + getCode() }, css: {'_active': (getCode() == isChecked())}">
Not brilliant but well...
Upvotes: 0
Reputation: 1747
This piece of code is redundant, as the css data-bind is getting overwrite with your attr binding.
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}, attr: {'class': getCode()}">
This is how you can do your dynamic class (assumption these properties are observable):
<div class="payment-method" data-bind="css: CSS">
self.CSS = ko.computed(function() {
var code = self.getCode();
var isChecked = self.isChecked();
return code + ' ' + (code == isChecked ? '_active' : '');
}, viewModel);
Upvotes: 3