Skip to content

Magento 2: issue while adding a on click event on KnockOut JS template file in minicart section

I want to show some recommended items based on each item added in the cart.
I have added those recommended items in the customer data.
And fetching the data in the default.html file. I have added a anchor tag to add this item to the cart, but some how the click event is not working.

I have overrided some of the Magento default files in my custom module.

  1. app/code/Vendor/Module/view/frontend/layout/checkout_cart_sidebar_item_renderers.xml
<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="minicart">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="minicart_content" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="item.renderer" xsi:type="array">
                                    <item name="component" xsi:type="string">Vendor_Module/js/view/cart-item-renderer</item>
                                    <item name="config" xsi:type="array">
                                        <item name="template" xsi:type="string">Vendor_Module/minicart/item/default</item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>
  1. app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
    config: {
      
        map: {
            '*': {
                'Magento_Checkout/js/view/cart-item-renderer':'Vendor_Module/js/view/cart-item-renderer',
            }
        }
    }
};
  1. In the cart-item-renderer.js file i have added some code mentioned below.
define([
    'jquery',
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function ($, Component, customerData) {
    'use strict';

    return Component.extend({
        /**
         * Prepare the product name value to be rendered as HTML
         *
         * @param {String} productName
         * @return {String}
         */
        getProductNameUnsanitizedHtml: function (productName) {
            // product name has already escaped on backend
            return productName;
        },

        /**
         * Prepare the given option value to be rendered as HTML
         *
         * @param {String} optionValue
         * @return {String}
         */
        getOptionValueUnsanitizedHtml: function (optionValue) {
            // option value has already escaped on backend
            return optionValue;
        },
        getRecommendedItemData: function (productId) {
            var customerDataObject = customerData.get('cart');
            var cartData = customerDataObject();
            var dataObject = cartData.checkoutConfigProvider.recommended_items[productId];
            var finalArray = Object.keys(dataObject).map(function(key) {
                return dataObject[key];
            })
            console.log(finalArray)
            return finalArray;
        },

        addToCartOnClick: function (sku) {
            alert('==>', sku)
        }
    });
});

  1. Vendor_Module/minicart/item/default.html file
<li class="item product product-item" data-role="product-item">
    <div class="product">
        <!-- ko if: product_has_url -->
        <a data-bind="attr: {href: product_url, title: product_name}" tabindex="-1" class="product-item-photo">
            <!-- ko foreach: $parent.getRegion('itemImage') -->
                <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
            <!-- /ko -->
        </a>
        <!-- /ko -->
        <!-- ko ifnot: product_has_url -->
        <span class="product-item-photo">
            <!-- ko foreach: $parent.getRegion('itemImage') -->
                <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
            <!-- /ko -->
        </span>
        <!-- /ko -->

        <div class="product-item-details">
            <strong class="product-item-name">
                <!-- ko if: product_has_url -->
                <a data-bind="attr: {href: product_url}, html: $parent.getProductNameUnsanitizedHtml(product_name)"></a>
                <!-- /ko -->
                <!-- ko ifnot: product_has_url -->
                    <!-- ko text: $parent.getProductNameUnsanitizedHtml(product_name) --><!-- /ko -->
                <!-- /ko -->
            </strong>

            <!-- ko if: options.length -->
            <div class="product options" data-mage-init='{"collapsible":{"openedState": "active", "saveState": false}}'>
                <span data-role="title" class="toggle"><!-- ko i18n: 'See Details' --><!-- /ko --></span>

                <div data-role="content" class="content">
                    <strong class="subtitle"><!-- ko i18n: 'Options Details' --><!-- /ko --></strong>
                    <dl class="product options list">
                        <!-- ko foreach: { data: options, as: 'option' } -->
                        <dt class="label"><!-- ko text: option.label --><!-- /ko --></dt>
                        <dd class="values">
                            <!-- ko if: Array.isArray(option.value) -->
                                <span data-bind="html: $parents[1].getOptionValueUnsanitizedHtml(option.value.join('<br>'))"></span>
                            <!-- /ko -->
                            <!-- ko if: (!Array.isArray(option.value) && ['file', 'html'].includes(option.option_type)) -->
                                <span data-bind="html: $parents[1].getOptionValueUnsanitizedHtml(option.value)"></span>
                            <!-- /ko -->
                            <!-- ko if: (!Array.isArray(option.value) && !['file', 'html'].includes(option.option_type)) -->
                            <span data-bind="text: option.print_value || option.value"></span>
                            <!-- /ko -->
                        </dd>
                        <!-- /ko -->
                    </dl>
                </div>
            </div>
            <!-- /ko -->

            <div class="product-item-pricing">
                <!-- ko if: canApplyMsrp -->

                <div class="details-map">
                    <span class="label" data-bind="i18n: 'Price'"></span>
                    <span class="value" data-bind="i18n: 'See price before order confirmation.'"></span>
                </div>
                <!-- /ko -->
                <!-- ko ifnot: canApplyMsrp -->
                <!-- ko foreach: $parent.getRegion('priceSidebar') -->
                    <!-- ko template: {name: getTemplate(), data: item.product_price, as: 'price'} --><!-- /ko -->
                <!-- /ko -->
                <!-- /ko -->

                <div class="details-qty qty qty-controls-wrap">
                    <label class="label" data-bind="i18n: 'Qty', attr: {
                           for: 'cart-item-'+item_id+'-qty'}"></label>
                    <a class="icon-minus qty-minus"></a>                    
                    <input data-bind="attr: {
                           id: 'cart-item-'+item_id+'-qty',
                           'data-cart-item': item_id,
                           'data-item-qty': qty,
                           'data-cart-item-id': product_sku
                           }, value: qty"
                           type="number"
                           min="0"
                           size="4"
                           class="item-qty cart-item-qty"/>
                    <a class="icon-plus qty-plus"></a>
                    <button data-bind="attr: {
                           id: 'update-cart-item-'+item_id,
                           'data-cart-item': item_id,
                           title: $t('Update')
                           }"
                            class="update-cart-item"
                            style="display: none">
                        <span data-bind="i18n: 'Update'"></span>
                    </button>
                </div>
            </div>

            <div class="product actions">
                <!-- ko if: is_visible_in_site_visibility -->
                <div class="primary">
                    <a data-bind="attr: {href: configure_url, title: $t('Edit item')}" class="action edit">
                        <span data-bind="i18n: 'Edit'"></span>
                    </a>
                </div>
                <!-- /ko -->
                <div class="secondary">
                    <a href="#" data-bind="attr: {'data-cart-item': item_id, title: $t('Remove item')}"
                       class="action delete">
                        <span data-bind="i18n: 'Remove'"></span>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div class="message notice" if="$data.message">
        <div data-bind="text: $data.message"></div>
    </div>

<!-- Custom Code -->
    <div class="data-recommend-wrapper">
        <div class="recommended" style="background:#eeeeee" data-options='{"swap":true}'>
            <div><strong>WE RECOMMEND ALSO</strong></div>
        </div>
        <div class="recommended-products">
            <table>
                <tbody data-bind="foreach: $parent.getRecommendedItemData(product_id)">
                    <tr>
                        <td>
                            <a data-bind="attr: {href: url, title: name}"> <span data-bind="text: name"></span> <span class="price" data-bind="text: price"></span></a>
                        </td>
                        <td width="16px">
                            <a data-bind="attr:{'data-role': 'direct', 'data-tooltip': 'Click to Add to cart', 'data-product': sku}, click:$parent.addToCartOnClick(sku)">
                                Add To Cart
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</li>

The click event should while clicking on the anchor tag.