Search code examples
blazormudblazor

MudBlazor ChipSet - selecting chips programmatically


I need to implement a "Select all" functionality whereby the user can select all chips via a button click, rather that clicking each item (which can be many!)

                            
<MudButton Variant="Variant.Outlined" 
           OnClick="(() => AllChips.ToList().ForEach(x => x.IsSelected = true))">
    Select all media
</MudButton>
                            
<MudChipSet SelectedChips="@SelectedChips" 
            MultiSelection="true" 
            Filter="true">
     @foreach (var chip in AllChips)
     {
          <MudChip Text="@chip.Text" />
     }
</MudChipSet>

I've explored the IsSelected and Default properties of a MudChip to no avail. The tooltip I get is that those properties should not be set outside of their component.

Is this possible to achieve with MudChipSet?


Solution

  • Firstly, you need to bind the SelectedChips value. Your current code shows SelectedChips="@SelectedChips", however to make it two-way bindable, it should actually be @bind-SelectedChips="SelectedChips". Then you'd be able to update the bound value.

    Updating the values becomes as simple as

        private void SelectAll()
        {
            SelectedChips = AllChips.ToArray();
        }
    

    Here's a quick Try.MudBlazor example