Skip to content

MatChipSet: set_SelectedChips cannot be used to preselect chips #671

Open
@peterthomastlc

Description

@peterthomastlc

When using MatChipSet.SelectedChips to preselect displayed chips in OnAfterRender, the comparison is done on a Hash of the MatChip, so a match will never be found.
As a result, chips cannot be preselected. Suggested fix below...

Reproduction Steps

  1. Use the code in the sample/demo application on the 'Chip' page.

  2. In the 'Filter ChipSet' section, replace the line
    MatChip[] selectedChips = null;
    with
    MatChip[] selectedChips = new MatChip[] { new MatChip() { Label = "Wedges" } };

  3. In the Razor file, add a ref value to the MatChipSet:-

     <MatChipSet @ref="filterChipset" Filter="true" @bind-SelectedChips="selectedChips">
    
  4. Override the OnAfterRender method to set the selected chips:-

        protected override void OnAfterRender(bool firstRender)
         {
             if (firstRender)
                 filterChipset.SelectedChips = selectedChips;
         }
    

Expected Result
The 'Wedges' chip should be selected when the page is shown.

Actual Result
All chips are deselected.

Suggested Fix
In MatChipSet.cs, at line 75, match on the Label value, not a hash of the MatChip object:-
Replace

var selected = new HashSet<MatChip>(value);
foreach (var chip in _chips)
    chip.IsSelected = selected.Contains(chip);

With

var selected = new HashSet<string>(value.Select(x => x.Label));
foreach (var chip in _chips)
    chip.IsSelected = selected.Contains(chip.Label);

I'd have submitted a pull request, but I'm not a registered contributor...

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions