Read More
Read More
Menu Close

    How to use Knockout JS on custom template in Magento2

    In this blog we will learn about Knockout JS in magento2.

    How to use Knockout JS on custom template in Magento2

    In Magento 2 main chunk of Knockout JS is used at checkout page. You are not bound to use knockout JS on Checkout page only. As a developer we can Initialize Knockout JS on our custom module’s template files.

    1. Create a template phtml file.

    File:// Webkul/Knockout/view/frontend/templates/account/knockout.phtml
    Create XML file to load this phtml file.

    <?xml version="1.0"?>
    <!--
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_Knockout
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    -->
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <update handle="customer_account"/>
        <body>
            <referenceContainer name="content">
                <block class="Webkul\Knockout\Block\Account" name="customer_account_knockout_test" template="Webkul_Knockout::account/knockout.phtml" cacheable="false"/>
            </referenceContainer>
        </body>
    </page>
    

    Now open the phtml file, Webkul/Knockout/view/frontend/templates/account/knockout.phtml to define KO initialization.

    Searching for an experienced
    Magento 2 Company ?
    Read More
    <div id="custom-component" data-bind="scope:'customcomponent'">
        <!-- ko template: getTemplate() --><!-- /ko -->
        <script type="text/x-magento-init">
        {
            "#custom-component": {
                "Magento_Ui/js/core/app": {
                   "components": {
                        "customcomponent": {
                            "component": "Webkul_Knockout/js/custom-component"
                        }
                    }
                }
            }
        }
        </script>
    </div>

    Now take a closer look at above defined code.
    M2 Initialize Js components by

    <script type="text/x-magento-init"> 
    

    When M2 initialize component, it first looks for the component id (which id #custom-component in our case.).
    Next you can see div element has attribute data-bind=”scope:’customcomponent'” Its shows that all the components initialized will load within this scope. you can find the key customcomponent with the same name within

    <script type="text/x-magento-init">

    Now create component js file which we have defined in our “component”: key

    File:// Webkul/Knockout/view/frontend/web/js/custom-component.js

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

    We can see above View-Model has a dependency, which extends all the KO components. uiCompoent file is Magento_Ui/js/lib/core/collection.js.

    Now Create template file which we have defined in our custom-component.js View-Model.

    File:// Webkul/Knockout/view/frontend/web/template/knockout-test.html

    <div class="component-wrapper">
        <div data-bind="text: 'Knockout Works'"></div>
    </div>

    Now clear the cache, run M2 static-content:deploy command, and hit this phtml template you will see a text Knockout Works.

    Let’s use some observable data binding

    Open the Model file which we have created before Webkul/Knockout/view/frontend/web/js/custom-component.js

    Update it with below code:

    define(['jquery', 'uiComponent', 'ko'], function ($, Component, ko) {
            'use strict';
            return Component.extend({
            	defaults: {
                    template: 'Webkul_Knockout/knockout-test'
                },
                initialize: function () {
                   this.customerName = ko.observableArray([]);
                   this.customerData = ko.observable('');
                    this._super();
                },
    
                addNewCustomer: function () {
                    this.customerName.push({name:this.customerData()});
                    this.customerData('');
                }
            });
        }
    );

    Now open html template file Webkul/Knockout/view/frontend/web/template/knockout-test.html

    Update it with below code.

    <div class="component-wrapper">
        <div class="field">
            <label class="label" for="email"><span data-bind="i18n: 'New Customer'"></span></label>
            <div class="control">
                <input name="customername"
                       id="customername"
                       type="text"
                       class="input-text"
                       data-bind="value: customerData">
            </div>
        </div>
        <div class="primary">
            <button type="button" class="action action-login secondary" data-bind="click: addNewCustomer">
                <span data-bind="i18n: 'Save'"></span>
            </button>
        </div>
    
        <div class="customer-list" style="width: 20%;background: gray;margin-top: 10px;" data-bind="foreach: customerName">
        	<li data-bind="text: name"></li>
        </div>
    </div>

    Again refresh cache and check.

    Now you will see a text box for Enter Customer Name, and Button. When add a customer it will be listed below.

    Knockout JS

    In JS model we use ko.ObservableArray([]) & ko.obervable() , both are uses to update UI automatically if they detect changes in view-model.

    In our example when you press save button obervableArray’s value gets update and in revert List of Customer gets update.

    . . .
    Discuss on Helpdesk

    3 comments

  • Mukesh Kumar Pandit
    Helpfull post. Thanks.
  • Banvari Lal
    Thanks for sharing this tutorial. It is really very good tutorial for basic knockout js integrate with Magento 2 thanks allot!
    • Mahesh Singh (Moderator)
      Banvari, i am glad to hear that it helped you!
  • Back to Top