Home > Back-end >  List parameter on child component not updating
List parameter on child component not updating

Time:03-18

I have a child component for filtering a search (DropdownFilter) which takes an input of a list of suggestions and a function to update that list.

For some reason DropdownFilter.Suggestions isn't being updated after it is initially set and I don't know how to update it again. Any information about how to update the property after it is initially bound would be great!

DropdownFilter.razor:

<input id="search" @onfocus="SearchFocused" @onblur="SearchUnfocused" @oninput="UpdateSearchText" />
@foreach (var suggestion in Suggestions)
{
    <p>@suggestion</p>
}

@code {
    [Parameter]
    public Action<string> SearchFieldChanged { get; set; }

    //[Parameter]
    //public RenderFragment<TSuggestion> SuggestionTemplate { get; set; }
    [Parameter]
    public List<string> Suggestions { get; set; }

    private bool searchFocus = false;
    private void SearchFocused(FocusEventArgs args) {
        searchFocus = true;
        //UpdateSearchText();
    }
    private void SearchUnfocused(FocusEventArgs args) => searchFocus = false;

    private void UpdateSearchText(ChangeEventArgs args)
    {
        SearchFieldChanged.Invoke((string)args.Value);
    }

    public void Refresh() {
        StateHasChanged();
    }
}

Index.razor:

@page "/example"

<div >
    <DropdownFilter @ref="dropdown" Suggestions="@maskResults" SearchFieldChanged="UpdateSearchResults" />
</div>

@code {
    DropdownFilter dropdown;

    public class MaskResult {
        public string name;
    }

    static readonly string[] allMasks = {
            "Electric",
            "Water",
            "Ground",
            "Fire",
            "Bug"
        };

    public List<string> maskResults = allMasks.ToList();

    private void UpdateSearchResults(string search)
    {
        search = search.ToLower();

        maskResults = allMasks.Where((mask) =>
        {
            return mask.ToLower().StartsWith(search);
        }).ToList();

        dropdown.Refresh();
    }
}

CodePudding user response:

I think that you are trying to create a Datalist, please check this answer:" datalist How to bind selected item to object

CodePudding user response:

If you add a StateHasChanged() call just here it should work:

private void UpdateSearchResults(string search)
{
    search = search.ToLower();

    maskResults = allMasks.Where((mask) =>
    {
        return mask.ToLower().StartsWith(search);
    }).ToList();

    StateHasChanged();  // Add this line
    dropdown.Refresh();
}

As I understand, if you update manually a Parameter of a component, there are some cases where Blazor does not get automatically the info that it needs to update its components. So if you call StateHasChanged, it will reevaluate all Parameters of the childreen of the component where you do the call.

I'll let someone correct me if I am wrong.

Thanks and good luck :)

  • Related