if else condition with Knockout

caras picture caras · Jul 24, 2017 · Viewed 11.2k times · Source

I'm very new at Knockout. I have a problem, how can I use if/else with Knockout.

For example like this

<ul class="list-group" data-bind="foreach: users">
    <li class="list-group-item" data-bind="click : setasUser">
        <i class="fa fa-circle text-success"></i> <span data-bind="text: name"></span>
    </li>
</ul>

I want to have a non-clikable item if username == x

How can I do this?

Answer

Bryan Dellinger picture Bryan Dellinger · Jul 24, 2017

unfortunately knockout does not have if else. however it does have an if binding and a ifnot binding.

here is a fiddle. http://jsfiddle.net/LkqTU/35843/

<ul class="list-group" data-bind="foreach: users">
<!-- ko ifnot: username() === 'x' -->
    <li class="list-group-item" data-bind="click : $parent.setasUser">
        <i class="fa fa-circle text-success"></i> <span data-bind="text: name"></span>
    </li>
  <!-- /ko -->
  <!-- ko if: username() === 'x' -->
  <li class="list-group-item" data-bind="text: name"> </li>
   <!-- /ko -->
</ul>