Do not select item until RadzenDropDown popup is closed

320 Views Asked by At

I'm using the RadzenDropDown control (source code here) in my .NET 7 Blazor project.

The issue I'm having is that if someone uses the keyboard to pop open the dropdown control to navigate through the list of dropdown items using the up/down arrow keys, the SelectedItemChanged and ValueChanged events trigger every time they move up and down an item in the list. Ideally, I would like these events to only trigger once the dropdown's popup window is closed, meaning the user has made their final selection.

Here is some sample code to demonstrate the problem. I have an environment picker control implemented using a dropdown. As soon as the user opens the dropdown popup (using the Enter key) and uses the arrow keys to move down in the list, the event fires and navigates them away from the site.

@using MyNamespace;
@inject WebsiteUrlsConfiguration WebsiteUrlsConfiguration
@inject WebAppInformation AppInfo
@inject NavigationManager NavigationManager

<RadzenDropDown TValue="Environments" Data=@EnvironmentOptions Value=AppInfo.Environment 
  ValueChanged="NavigateToEnvironment" />

@code {
    private IEnumerable<Environments> EnvironmentOptions =
        Enum.GetValues<Environments>()
        .Where(x => x != Environments.Unknown);

    private void NavigateToEnvironment(Environments selectedEnvironment)
    {
        var urlToNavigateTo = WebsiteUrlsConfiguration.GetUrlForEnvironment(selectedEnvironment);
        NavigationManager.NavigateTo(urlToNavigateTo);
    }
}

Is there a way to test if the dropdown popup window is open or not? Or perhaps a different event I should hook into besides ValueChanged or SelectedItemChanged?

Thanks,

1

There are 1 best solutions below

1
On

I spun up a project and was able to listen to @onkeyup like so. You can extract the value with SelectedItem.

<RadzenDropDown TValue="int" Data=@Numbers Value=4 SelectedItem="Selected" @onkeyup="NavigateToEnvironment" />

@code {
    private IEnumerable<int> Numbers = new int[] { 3, 4, 5 };
    private int Selected { get; set; }

    private async Task NavigateToEnvironment(KeyboardEventArgs e)
    {
        if (e.Code == "Enter")
        {
            Console.WriteLine(Selected);
            // do something
        }
    }
}

There are similar event bindings for @onclick available.

As a side note, I'd be attentive to designing unsurprising websites with semantic HTML. Immediately navigating from a page when entering a dropdown box sounds surprising! However, I don't want to tell you how to design your website and trust that you have good reason for not separating this into a dropdown to select and an anchor to navigate.