Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter items in multiple material select

I want to filter on multiple select in Material2.

To do that I try to use a simple filter pipe on mat-option something like so: transform() { ... return value.filter(v => v.value === argtext); }

Here is the problem,

First, I select some items.

Then, I filter by keyword I got filtered new items.

Now I can see my previous selection has lost.

This is because Material build the options every time the filter change them. and clear the selection each time also. So My idea for using pipe it's not working for me.

This is the example with the select and the text here

  1. In my example select "Extra cheese", "Sausage".
  2. In the textbox type "Mushroom".
  3. Select this item. (Mushroom)
  4. you can see in the toppings below that only "Mushroom" selected and "Extra cheese", "Sausage" has been lost.

Thanks for reading/help

like image 878
Shlomi Levi Avatar asked Aug 09 '26 23:08

Shlomi Levi


1 Answers

Instead of filtering toppingList with a pipe you can just hide options based on search input value.

Add this to style.scss:

.hide {
  display: none;
}

And in your component HTML:

   <mat-form-field>
    <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
      <mat-option *ngFor="let topping of toppingList" [class.hide]="text.value !== '' && topping.value.toLowerCase().indexOf(text.value.toLowerCase()) === -1" [value]="topping">
        {{topping.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>

Updated stackblitz example

like image 86
Mateusz Witkowski Avatar answered Aug 12 '26 13:08

Mateusz Witkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!