Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using knockout to set css class with an if condition

Tags:

knockout.js

I want to set a bootstrap css class to a span with if condition (up to the binded value). I have isApproved field in a list, I want to see the field with 'label-success' class when its active and 'label-important' class when its inactive

I added this line, but all the time it's taking the first class

data-bind="     text: isApproved,     css: isApproved = 'true' ? 'label label-important' : 'label label-important'" 

Is it possible in the html or I should add a computed field on my VM?

like image 909
Wasim Avatar asked Jul 31 '13 12:07

Wasim


People also ask

How do I declare a class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do I bind a CSS class in angular 6?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.

What is Ko computed in knockout JS?

In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.


2 Answers

If I understood you right, this is the binding you are looking for.

 data-bind="text: isApproved, css: {     'label' :  true,     'label-success' :  isApproved(),     'label-important':  !isApproved()  }" 

I hope it helps.

like image 195
Damien Avatar answered Sep 20 '22 14:09

Damien


Ternary operator example

<span class="label"     data-bind="text: isApproved,                css: isApproved() == true ? 'label-success' : 'label-important'"> </span> 
like image 22
Armand Avatar answered Sep 20 '22 14:09

Armand