Drupal - set html 'lang' to match node 'langcode'?

Job ID: 32786123

Budget: $30 – $50 USD

I would like to change a node's html 'lang' from site's default to the node's 'langcode'.

For example, if I create a node and while creating I select French as the language, I would like the page's html 'lang' to "fr"

So far I have this but I'm getting an error of 'Error: Call to a member function getFormObject() on null'

/** @var \Drupal\Core\Template\Attribute $html_attribute */
$html_attribute = $variables['html_attributes'];
$node_langcode = $node->get('langcode')->value;
if ($html_attribute->hasAttribute("lang")) {
$html_attribute->removeAttribute('lang');
$html_attribute->setAttribute('lang', $node_langcode);
}
Deliverables
Code that changes the node's html attribute to the node langcode.
Related categories: PHP JavaScript Drupal