我正在尝试构建一个具有多个(动态创建的)选择下拉列表的组件,以用作搜索过滤器。选定的过滤器应该显示在我正在工作的芯片中,我遇到的问题是在删除过滤器时我想更新下拉列表中的选定选项。
我在这里阅读了几个相关的答案,但无法正常工作。我是否遗漏了一些明显的东西?
这是一个 Stackblitz:https://stackblitz.com/edit/angular9-material-baseline-yxr1sw
从每个选择中选择一个选项,然后移除一个筹码 - 两个选择都被清除。
我需要更改什么才能让它们正确更新?
最佳答案
您正在使用 item.value
作为 mat-option
的 value
。
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);
}
);
}
关于Angular mat-select,设置值有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64554561/