knockout.js Bindings If / ifnot


Example

You can use the if binding to determine whether or not the child elements of the node should be created.

<div class="product-info">
    <h2>  Product1  </h2>
    <img src="../products/product1.jpg"/>
    <span data-bind="if:featured">
        <span class="featured"></span>
    </span>
    <span data-bind="ifnot:inStock">
        <span class="out-of-stock"></span>
    </span>
</div>
     
<script>
    ko.applyBindings({
        product: {
            featured: ko.observable(true),
            inStock: ko.observable(false)
        }
    });
</script>

The inverse of the if binding is ifnot

<div data-bind="ifnot: someProperty">...</div>

is equivalent to

<div data-bind="if: !someProperty()">...</div>

Sometimes, you'll wan't to control the presence of elements without having to create a container (typically for <li> elements in a <ul> or <option> elements inside a <select>)

Knockout enables this with containerless control flow syntax based on comment tags like so:

<select>
  <option value="0">fixed option</option>
<!-- ko if: featured-->
  <option value="1">featured option</option>
<!-- /ko -->
</select>