Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular mat-select, having trouble setting values

I am trying to build a component that has several (dynamically created) select dropdowns, to use as search filters. The selected filters should show in chips, which I have working, the problem I have is when removing a filter I want to update the selected options in the dropdowns.

I have read several related answers here but can't get it working. Am I missing something obvious?

Here is a Stackblitz: https://stackblitz.com/edit/angular9-material-baseline-yxr1sw

Choose an option from each select, then remove one chip - both selects are cleared.

What do I need to change to get them to update correctly?

like image 794
Sparrowhawk Avatar asked Sep 23 '26 06:09

Sparrowhawk


1 Answers

You're using item.value as the value for your mat-option.

filter-select.component.html

<mat-option *ngFor="let item of productFilter.options" [value]="item.value">{{item.name}}</mat-option>

Those values are primitive so you don't need a compareWith function.

<mat-select multiple [formControl]="filterSelect" (openedChange)="openedChange($event)">

// [compareWith]="compareFn" removed

And only set your formControl to those item values

filter-select.component.ts

ngOnInit() {
  this.subscription = this.productFiltersService.selectedFiltersChanged.subscribe(
    (newFilters: ProductFilter[]) => {
      const values = newFilters
        .find(f => f.name === this.productFilter.name)
        .options
        .filter(o => o.isSelected) // <-- only take selected options
        .map(o => o.value); // <-- only take values
      console.log("filterSelect setValue", values);
      this.filterSelect.setValue(values);
    }
  );
}

https://stackblitz.com/edit/angular9-material-baseline-vguwxd?file=src/app/filter-select.component.html

like image 164
frido Avatar answered Sep 26 '26 16:09

frido



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!