How do I update an Input's Datalist without losing focus on the input in Blazor?

Viewed 602

This is in Blazor Server. I'm trying to build a search functionality that searches the database starting with the third character typed so the datalist is empty when the page loads and should populate when the user starts typing.

The list I receive from the database is populated and the page does go through the foreach loop to build the options in the datalist but the datalist does not show itself (and is also not viewable in the browser debugger) until after focus is lost on the input element and regained (pressing escape is what I usually do).

The only way I have been able to make this work/display data is if the datalist's display is visible, which does not result in the dropdown list and if I prepull all the data from the database on the page's initialization, which does not work as I do not want to pull all the elements from the database every time the page is loaded.

The call to the database is awaited also.

The input and datalist code:

<datalist id="txtSearch">
    @foreach (var item in this.facilities)
    {
        <option value="@item.Name"/>

    }
</datalist>

<input autocomplete="on" type="text" list="txtSearch" @oninput="@Search" @onchange="@GetFacility"/>

If any more information is needed I can provide. Thank you.

1 Answers

I can't test it right now, but Blazor has a focus method. Maybe try something like:

<input @ref="MyList" autocomplete="on" type="text" list="txtSearch" @oninput="@Search" @onchange="@GetFacility"/>

@code {
    ElementReference MyList {get; set;}

    async Task SomeAsyncMethod(){
        // Load stuff
        MyList.FocusAsync();
    }
}
Related