My template file code is
$listBlock = $this->_listBlock;
$addToCartUrl = $listBlock->getAddToCartUrl($_product);
?>
<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post">
<?php echo $block->getBlockHtml('formkey')?>
<button type="submit" title="Add to Cart" class="action tocart primary">
<span>Add to Cart</span>
</button>
</form>
My Block code is
<?php
namespace Vendor\Modulename\Block;
class AddProduct extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public $_listBlock;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Block\Product\ListProduct $listBlock,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->_listBlock = $listBlock;
parent::__construct($context, $data);
}
}