Magento – How to i open mini cart on add of a product

cartmagento-2.1magento2mini-cart

I am using the below link to create an observer.

Magento 2 Open minicart when item is added

My question is what code will come here

if ($cartUpdated) {
    // open mini cart
}

How can i open the mini cart?

Best Answer

You need to create module for that

create default.xml in : Company/ModuleName/view/frontend/layout/default.xml

<referenceContainer name="content">
  <block class="Magento\Framework\View\Element\Template" name="minicart.autoopen" template="Company_ModuleName::minicart_open.phtml"/>
</referenceContainer>

Now create Company/ModuleName/view/frontend/templates/minicart_open.phtml

Inside minicart_open.phtml we need to call our js file (component) by attaching it to the parent div of the minicart. In this case, [data-block='minicart'].

<script type="text/x-magento-init">
{
     "[data-block='minicart']" : {
        "Company_ModuleName/js/view/minicart_open" : {}
     }
}
</script>

Create Company/ModuleName/view/frontend/web/js/view/minicart_open.js

define(["jquery/ui","jquery"], function(Component, $){
    return function(config, element){
        var minicart = $(element);
        minicart.on('contentLoading', function () {
            minicart.on('contentUpdated', function () {
                minicart.find('[data-role="dropdownDialog"]').dropdownDialog("open");
            });
        });
    }
});

Now mini cart will open automatically after product added.

Please reefer this link: https://github.com/navinbhudiya/magento2-minicart-open. I think you are reusing this and you can find the files not mentioned here in this link.