How to add multiple CSS classes using Bindngs

I have a data binding where I need to apply two css classes

data-bind ="css: isHiddenStage"

      

isHiddenStage ==> function returns css class based on some logic, This works great and I want to apply other css classes based on some condition

css:{ my-class:$index() + 1 === 10 }

      

Note. Here, I cannot use the isHiddenStage function to check the condition So I got this:

    data-bind ="css: isHiddenStage, css:{ my-class:$index() + 1 === 10 }"

      

Which doesn't work, perhaps because I can't use css twice in the binding. Is there any alternative.

Hello

+3


source to share


2 answers


There cannot be multiple CSS anchors in one element. Create a function that returns all space separated css classes to be used in one css binding.

Html

<div data-bind="css: getCssClassesForIndex($index)"></div>

      



View Model

this.getCssClassesForIndex = function (index) {
    var cssClasses = this.isHiddenStage() || '';
    if ((index + 1) === 10) {
        cssClasses += ' my-class';
    }
    return cssClasses;
}.bind(this);

      

+3


source


Something like:

data-bind ="css:{ isHiddenStage: true, 'my-class': $index() + 1 === 10 }"

      

This way the isHiddenStage () class will always be applied because its condition is always true.



Note that I was putting 'my-class' in quotes because it was not a valid identifier.

Link source for knockout documentation

+1


source







All Articles