Magento – Remove My Account top bar when user is not logged in

layoutmagento2xml

i want to remove magento top link My Account if user is not logged in ,i do not want to modify core files, i tried to get solution but could not find any working one .

i tried below method in : "Magento_Customer/layout/default.xml"

<customer_logout>
    <referenceBlock name="top.links">
        <referenceBlock name="my-account-link" remove="true" />
    </referenceBlock>
</customer_logout>

but it gives Error :

Element 'customer_logout': This element is not expected. Expected is
one of ( attribute, block, referenceBlock, referenceContainer,
container, move, uiComponent ).

Best Answer

There is no customer_logout layout handle in M2, so You can't do with xml, there is no more customer_logged_in, customer_logged_out like M1

Solution1: It's depends to your theme, try to enable the path hints, and find if you find the phtml who display "My Account" Then add if($block->customerLoggedIn()) condition arround that link.

Solution2: If your link is added via Xml, you have to create an observer with layout_load_before event, then you can add $layout->addHandle('customer_logged_in') something like:

$layout = $observer->getEvent()->getLayout();
if ($this->customerSession->isLoggedIn()) {
    $layout->getUpdate()->addHandle('customer_logged_in');
} else {
    $layout->getUpdate()->addHandle('customer_logged_out');
}

Check this link, you have a full solution.