Search code examples
cssclassmagentoknockout.jsdata-binding

add dynamic class with css binding


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?


Solution

  • 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...