skip to Main Content

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


  1. Chosen as BEST ANSWER

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


  2. 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);
    
    Login or Signup to reply.
  3. Another example should anyone need it

    <div data-bind="attr: { 'class': 'mainClass' + (dynamicClassSetOnce ? ' ' + dynamicClassSetOnce : '' }, css: { 'mainClass--focussed': isFocussed }">
    ...
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search