首页 > 解决方案 > 在 selectionChange 内/之后更改选定的 mat-chips

问题描述

这个概念是我想根据mat-chips选择的页面过滤显示的信息。

的HTML:

<mat-chip-list [multiple]="true">
    <mat-chip
       class="item-filter-mat-chip"
       *ngFor="let itemFilter of itemFilters"
       [selectable]="true"
       [selected]="itemFilter.selected"
       [value]="itemFilter"
       (selectionChange)="updateItemFilter($event)"
       (click)="chip.toggleSelected()"
       #chip="matChip">
       {{itemFilter.displayValue}}
  </mat-chip>
</mat-chip-list>

TypeScript 项目:

export interface ItemFilter {
    itemType: ItemType[];
    displayValue: string;
    selected: boolean;
}

mat-chips但是,如果未选择所有其他芯片,我希望其中之一成为选择的“默认”。但是,似乎进行选择更改的逻辑必须发生在 中updateItemFilter,然后创建一个ExpressionChangedAfterItHasBeenCheckedError. 这是因为我试图在selectionChange调用的方法中更改选择值。

情况是这样的。已选择默认过滤器。选择不同的过滤器后,应取消选择默认过滤器。可以选择多个其他过滤器。如果选择了默认过滤器,则应取消选择所有其他过滤器。

标签: htmlangulartypescript

解决方案


深入研究后,修复似乎不再在 mat-chip 上使用(selectionChange),而是更改选择并更新自定义(单击)方法内的过滤器。

<mat-chip-list [multiple]="true">
    <mat-chip
        class="item-filter-mat-chip"
        *ngFor="let itemFilter of itemFilters"
        [selectable]="true"
        [selected]="itemFilter.selected"
        [value]="itemFilter"
        (click)="updateItemFilter(chip)"
        #chip="matChip">
        {{itemFilter.displayValue}}
    </mat-chip>
</mat-chip-list>

推荐阅读