How to get simple products from a configurable product in magento 2

In this blog we’ll going to get the simple products in a block and from object manager.

First we’re going to fetch child products from a block.

<?php
namespace Custom\Module\Block\Product\View;

use \Magento\Framework\View\Element\Template;

class Sample extends Template
{
protected $_productRepository;

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Model\ProductRepository $productRepository)
{
$this->_productRepository = $productRepository;
parent::__construct($context);
}

public function getProductById($id)
{

$product = $this->_productRepository->getById($id);
$_children = $product->getTypeInstance()->getUsedProducts($product);
foreach ($_children as $child){
    echo “Here are your child Product Ids “.$child->getID().“\n”;
}
}

}

Below is how to get simple products from an object manager.

<?php
$configProduct = $objectManager->create(‘Magento\Catalog\Model\Product’)->load($product_id);
$_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);
foreach ($_children as $child){
    echo “Here are your child Product Ids “.$child->getID().“\n”;
}
echo “count: “.count($_children);