Magento, Magento 2

How to use if else in Knockout JS in Magento 2

How to use if else in Knockout JS in Magento 2

In this tutorial, I will explain you how to use if else condition in knockout JS in Magento 2. Knockout JS majorly used for checkout and UIComponent in Magento 2 and also its difficult part of Magento 2.

So, If we want to if else condition base code in knockout js as like php then, we can add? Here, I will explain example with steps by steps.

You may also like this :

1) First of all, Let’s assume that you have created simple module from above link of knockout js. Then, Just update code in your app/code/RH/KnockoutExe/view/frontend/web/template/knockout-test-example.html html file to check output :

Way 1 : 

<!--
/**
 * Created By : Rohan Hapani
 */
-->
<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 :

<!--
/**
 * Created By : Rohan Hapani
 */
-->
<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) Then, You need to update code in your app/code/RH/KnockoutExe/view/frontend/web/js/rhkojs.js js file with below code :

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

In this file, You can see that x is observable variable and set as TRUE. For Html, I added 2 ways to add if else condition. You can use any of them.

Now, Just need to execute this command :

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

That’s it !!!

I hope this blog is easy to understand about how to use if else condition in knockout JS in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing 🙂

Tagged ,