Knockout Js in Magento 2

Knockout Js in Magento 2

In Magento 2 Knockout is used in most of places like in Admin grid,form uploader’s and in frontend most usage of Knockout is in checkout page. 
In today’s Post I will explain how touse Knockout js in Magento 2.

What is Knockout Js (KO)?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), Knockout  can help you implement it more simply and maintainably. In 

You can find More about the How Core Knockout work and what are the function of Knockout in Official Document

How to Use Knockout Js in Magento 2?

You can define your Knockout component in two different way.

  1. Using layout XML
  2. Using template file.

1. Using Layout XML

First in your module create layout file and add the following code in it.

Path: app/code/Rk/KoDemo/view/frontend/layout/kodemo_index_index.xml

<?xml version="1.0"?>
<page layout='1column' xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" >
      <referenceContainer name="content">
          <block class="Rk\KoDemo\Block\Index\KoDemo" before="-" template="kodemo.phtml">
                  <argument name="jsLayout" xsi:type="array">
                      <item name="components" xsi:type="array">
                          <item name="kodemo" xsi:type="array">
                              <item name="component" xsi:type="string">Rk_KoDemo/js/view/kodemo</item>
                              <item name="config" xsi:type="array">
                                  <item name="template" xsi:type="string">Rk_KoDemo/kodemo</item>


And then create block file and paste below code in that block file.

Path: app/code/Rk/KoDemo/Block/Index/KoDemo.php


namespace Rk\KoDemo\Block\Index;

class KoDemo extends \Magento\Framework\View\Element\Template

     * @var array
    private $layoutProcessors;

     * Index constructor.
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param array $layoutProcessors
     * @param array $data
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $layoutProcessors = [],
        array $data = []
    ) {
        parent::__construct($context, $data);
     * Retrieve serialized JS layout configuration ready to use in template
     * @return string
    public function getJsLayout()
        foreach ($this->layoutProcessors as $processor) {
            $this->jsLayout = $processor->process($this->jsLayout);
        return parent::getJsLayout();


Now in your phtml file add below code.

Path: app/code/Rk/KoDemo/view/frontend/templates/kodemo.phtml

Note: scope:'kodemo' this scope name must match with components define in kodemo_index_index.xml

<div id="kodemo" data-bind="scope:'kodemo'"> <!-- ko template: getTemplate() --><!-- /ko --> <script type="text/x-magento-init"> { "#kodemo": { "Magento_Ui/js/core/app":<?php echo $block->getJsLayout()?> } } </script> </div>

Our Knockout component initialize process finished here. Now, we have to create HTML and JS file.

Now, I will show you how we can initialize Knockout component using second method.

2. Using Template File.

Create layoutfile and paste below code.

Path: app/code/Rk/KoDemo/view/frontend/layout/kodemo_index_index.xml

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="index.kodemo" template="Rk_KoDemo::kodemo.phtml"/>

Create template file and paste below code. 

<div id="kodemo" data-bind="scope:'kodemo'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
            "#kodemo": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "kodemo": {
                            "component": "Rk_KoDemo/js/view/kodemo",


Note: In template file we have define #kodemo It means Our Knockout will initialize only when page element have ID as kodemo . If you want to initialize Knockout always then you have to replace “#kodemo” with “*”. 

You can use css class name and other attributes also to initialize Knockout. 

Now, We have to create JS and html (template) file to display data on page. JS and Template file is comman in both method (layout and template).

Create js file and paste below code.

Path: app/code/Rk/KoDemo/view/frontend/web/js/view/kodemo.js

], function (ko, Component) {
    "use strict";
    return Component.extend({
        initialize: function () {
        getTitle: function () {
            return 'Knockout Tutorial';

Create html template file and paste below code.

Path: app/code/Rk/KoDemo/view/frontend/web/template/kodemo.html

   <h1 data-bind="text:getTitle()"></h1>


Hope you find this Tutorial is helpful. Do comment if you face any issue or Contact me If you want any help or customization in your existing Project or Extension.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top