How to use if else in Knockout JS in Magento 2?

This tutorial will bring in certain ways to use if else condition in knockout JS in Magento 2. Knockout JS is an important factor used for checkout and UI Component in Magento 2. It is known to be a difficult part of Magento 2. So, if you are planning to use if else condition base code in knockout js just like PHP, here is a step by step example of what you should be doing.

1) We assume that you have already created a simple module from the above link of knockout js.

Once done, just update the following code in your app/code/MD/KnockoutExe/view/frontend/web/template/knockout-test-example.html html file to check the output :

Way 1 : 

<div class="component-class">
    <!-- ko if: x -->
    <div data-bind="text: 'Value of X is TRUE.'"></div>
    <!-- /ko -->
    <!-- ko ifnot: x -->
    <div data-bind="text: 'Value of X is FALSE.'"></div>
       <!-- /ko -->
</div>

Way 2 :

<div class="component-class">
<div if="x"data-bind="text: 'Value of X is TRUE.'"></div>
<div ifnot="x" data-bind="text: 'Value of X is FALSE.'"></div>
</div>

2) Thereafter, you need to update code in your app/code/MD/KnockoutExe/view/frontend/web/js/mdkojs.js js file with below code :

define(['jquery', 'uiComponent', 'ko'], function ($, Component, ko) {
'use strict';
return Component.extend({
defaults: {
template: 'MD_KnockoutExe/knockout-test-example',
x : ko.observable(true),
},
initialize: function () {
this._super();
}
});
}
);

You can see that x is observable variable and set as TRUE. For Html, we have added 2 ways to add if-else condition. Any of them can be used. Once done, you just need to execute this command :

php bin/magento s:up
php bin/magento s:s:d -f 
php bin/magento c:c

Conclusion:

With the above-mentioned steps, you can easily use the if-else condition in Knockout JS on your Magento store.

Hope we did not miss anything, still if you need our professional help with Magento Certified Developer, contact us and get the guidance by the best of our developers.