Blazored / Typeahead

Typeahead control for Blazor applications
https://blazored.github.io/Typeahead/
MIT License
439 stars 103 forks source link

[Feature] Make internal clear method public so developers can programmatically reset the component #210

Open davidrhicks opened 3 years ago

davidrhicks commented 3 years ago

I am using Blazored Typeahead within a form. Is there a way to reset the component without having to use javascript? I have tried changing the selected value programmatically but that causes the entire page to reload. Basically I need the input to do whatever it does when the user clicks on the X to clear the value.

timbze commented 3 years ago

.NET has a weird issue when @bind-Value is tied to a property directly in class. I don't know if that is the issue, but maybe. Let me demonstrate by example and show what I think will fix it for you.

@code {
    private string _itemSelectedInClass { get;set; }
    private ReportFilters _reportFilters { get;set; } = new ReportFilters();

    private class ReportFilters
    {
        public string ItemSelected { get;set; }
    }
}
<BlazoredTypeahead
    EnableDropDown="true"
    SearchMethod="SearchList"
@*    @bind-Value="@_itemSelectedInClass" *@
    @bind-Value="@_reportFilters.ItemSelected">
    <SelectedTemplate Context="item">
        @item
    </SelectedTemplate>
    <ResultTemplate Context="item">
        @item
    </ResultTemplate>
</BlazoredTypeahead>

If you'll use the commented line (with @* *@), it's possible that the page will do a reload. I have had this when binding inputs to properties directly in the class. But if using the uncommented line (property in a sub-class), it should work.

When you call _reportFilters.ItemSelected = null; somewhere in your code, the typeahead should be cleared.

chrissainty commented 3 years ago

Hi @timbze, thanks for raising this issue. I think the best way to solve this is to expose our internal clear method. There are quite a few operations we need to do to reset the component and exposing this method would make things very clean for developers. It would look something like this:

<BlazoredTypeahead
    @ref=""
    EnableDropDown="true"
    SearchMethod="SearchList"
    @bind-Value="@_itemSelectedInClass">
    <SelectedTemplate Context="item">
        @item
    </SelectedTemplate>
    <ResultTemplate Context="item">
        @item
    </ResultTemplate>
</BlazoredTypeahead>

<button @onclick="_typeahead.Clear">Clear Typeahead</button>

@code {
    private BlazoredTypeahead<string, string> _typeahead;
}