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 :
[dm_code_snippet background=”no” background-mobile=”no” slim=”no” line-numbers=”no” bg-color=”#fff” theme=”dark” language=”markup” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
<!-- /** * 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>
[/dm_code_snippet]
Way 2 :
[dm_code_snippet background=”no” background-mobile=”no” slim=”no” line-numbers=”no” bg-color=”#fff” theme=”dark” language=”markup” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
<!-- /** * 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>
[/dm_code_snippet]
2) Then, You need to update code in your app/code/RH/KnockoutExe/view/frontend/web/js/rhkojs.js js file with below code :
[dm_code_snippet background=”no” background-mobile=”no” slim=”no” line-numbers=”no” bg-color=”#fff” theme=”dark” language=”javascript” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
/**
* 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();
}
});
});
[/dm_code_snippet]
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 :
[dm_code_snippet background=”no” background-mobile=”no” slim=”no” line-numbers=”no” bg-color=”#fff” theme=”dark” language=”shell” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
php bin/magento s:up php bin/magento s:s:d -f php bin/magento c:c
[/dm_code_snippet]
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 🙂