角度垫选择,设置值有问题



我正在尝试构建一个组件,该组件具有多个(动态创建的(选择下拉列表,用作搜索过滤器。所选的过滤器应该显示在芯片中,我已经在工作了,我的问题是当删除过滤器时,我想在下拉列表中更新所选的选项。

我在这里读了几个相关的答案,但无法使其发挥作用。我是不是错过了一些显而易见的东西?

以下是Stacklitz:https://stackblitz.com/edit/angular9-material-baseline-yxr1sw

从每个选择中选择一个选项,然后删除一个芯片-两个选择都被清除。

我需要更改什么才能使它们正确更新?

您使用item.value作为mat-optionvalue

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

这些值是基元的,因此不需要compareWith函数。

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

并且只将你的formControl设置为那些项目值

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

最新更新