.netblazorblazor-webassemblymudblazor

MudBlazor MudChipSet - How to set selected MudChip programatically?


I'm using a couple of MudBlazors MudChip in a MudChipSet. The exact amount varies based on a the lenght of a list (creating on MudChip per object in that list).

Now I want to select one of these chips based on saved data. My approach was to create a List of MudChips with one per list item (only setting the "Text" property). I'm then filtering to get the one where "Text" is matching the string I have and set that result to the bind "selectedChip" variable.

However, that doesn't work. Any idea why?

See a demo here: try.mudblazor.com/snippet/wOweEzaxfXjVrtFe


Solution

  • Two things:

    1. You should not try to set the item on initialization but rather once the component has rendered. The ChipSet has a chance of being null when OnInitialized is being executed.
    2. You are creating a brand new list of chips instead of using the chips that are rendered by your ChipSet foreach loop.

    Changes:

        // Run this on first render to pre-set the selected chip
        protected override void OnAfterRender(bool firstRender) 
        {
            if (!firstRender) return; //exit if not first render
    
            selectedChip = availableChips.Single(e => e.Text == SelectedLocation);
    
            StateHasChanged();
        }
    

    Add a reference to the chips that are being rendered

        @foreach (var entry in GetWorkLocationHoursMock())
        {
            <MudChip @ref=ChipRef Text="@entry.Location" Color="Color.Primary"/> 
        }
    

    and add those items to your list, instead of creating new MudChip objects

        private MudChip ChipRef { set => availableChips.Add(value); }
    

    The end result should look like this