Blazor how to add outside-component events to a component?

Solution for Blazor how to add outside-component events to a component?
is Given Below:

I’m creating a dropdown menu button in Blazor.
The things I want the component to do is:

  1. Add buttons to the dropdown menu component
  2. The addable buttons in the menu need to be onclick-bindable
  3. The dropdown menu button onclick should open/close the menu
  4. When the menu is open and you press outside the component the menu needs to be closed

My current code:

Dropdown menu

<div class="more-options-menu-button">
<button @onclick="OnShowMenuClick" @onclick:stopPropagation="true">
    <svg height="24px" width="24px">
        <image [email protected] height="24px" width="24px"></image>
    </svg>
</button>
@if (Display)
{
    <section class="menu" @onclick:stopPropagation="true">
        @MenuOptions
    </section>
}
</div>
@code {
[Parameter]
public RenderFragment MenuOptions { get; set; }

private bool Display { get; set; }

private const string MoreOptionsIconUrl = "https://localhost:5001/svg/general/more_vert_24dp.svg";

public void Hide()
{
    this.Display = false;
}

public void OnShowMenuClick()
{
    this.Display = !this.Display;
}
}

MenuOption

<button id="Id" @onclick="OnClick">
@Title
</button>

@code {
[Parameter]
public string Title { get; set; }
[Parameter]
public EventCallback OnClick { get; set; }
[Parameter]
public string Id { get; set; }
}

How to use

 <OptionsMenuComponent>
            <MenuOptions>
                <MenuOptionComponent Id="remove" Title="Remove" OnClick="Remove" />
            </MenuOptions>
        </OptionsMenuComponent>

@code {
   private void Remove()
{
    Console.WriteLine("Removing...");
}
}

I can do with the above code everything except 4 (close menu when click on outside component).

How can I handle this event when it is not related to the scoped component?

Note: I found a Library which seems to handle every requirement I need but I’m not certain how they created the related component.

This question was already asked in this topic, but I was advised to create a new dedicated issue.

Have you tried using the onfocusout event? Documentation here

In your OptionsMenuComponent you can try this to see how it works:

<div class="more-options-menu-button">
<button @onclick="OnShowMenuClick" @onclick:stopPropagation="true" @onfocusout="Hide">
    <svg height="24px" width="24px">
        <image [email protected] height="24px" width="24px"></image>
    </svg>
</button>
@if (Display)
{
    <section class="menu" @onclick:stopPropagation="true">
        @MenuOptions
    </section>
}