如何以编程方式更改垫子芯片列表中垫子芯片的颜色?

M4V*_*V3N 5 angular-material angular

我正在使用 mat-chips 过滤表格,一切似乎都很好:

主页.html

<mat-chip-list>
   <mat-chip (click)="onSectorChipSelect(sector)" [color]="chipColor(sector)" *ngFor="let sector of sectors" selected>{{sector}}</mat-chip>
   <mat-chip (click)="clearSectors()">
     Clear 
   </mat-chip>
</mat-chip-list>
Run Code Online (Sandbox Code Playgroud)

home.ts将扇区添加到名为filtersSectors的列表中,该列表一次保存所有选定的扇区。

onSectorChipSelect(sector: string) {
 if (this.filteredSectors.includes(sector)) {
  this.filteredSectors.splice(this.filteredSectors.indexOf(sector), 1);
 } else {
  this.filteredSectors.push(sector);
 }
}
Run Code Online (Sandbox Code Playgroud)

home.ts如果选中,此方法会将芯片着色为蓝色(主要),否则保持白色(基本)。

chipColor(sector: string) {
  if (this.filteredSectors.includes(sector)) {
    return 'primary';
  }
  return 'basic';
}
Run Code Online (Sandbox Code Playgroud)

“问题”是chipColor()方法绑定到芯片的颜色属性,因此在主页组件中滚动或单击时会多次调用。我的猜测是每次浏览器呈现时,都会再次调用该方法?(我真的不知道,也许有人可以解释一下?)

大约有 20 个扇区,所以我猜这不是一个真正的性能问题?知道这很烦人,我认为这不是一个好习惯。但我怎么能改变呢?

到目前为止我尝试的是将每个芯片的颜色设置为白色(基本):

主页.html

<mat-chip (click)="onSectorChipSelect(sector)" color="basic" *ngFor="let sector of sectors" selected>{{sector}}</mat-chip>
Run Code Online (Sandbox Code Playgroud)

家.ts

  @ViewChild(MatChipList) chipList: MatChipList;
Run Code Online (Sandbox Code Playgroud)

使用 ViewChild 注释获取芯片列表,然后迭代芯片并设置它们的颜色,但这不起作用。选择第二个芯片后,第一个芯片再次变为白色。

onSectorChipSelect(sector: string) {
    if (this.filteredSectors.includes(sector)) {
      this.filteredSectors.splice(this.filteredSectors.indexOf(sector), 1);
    } else {
      this.filteredSectors.push(sector);
    }

    this.chipList.chips.forEach(chip => {
      if(this.filteredSectors.includes(chip.value)) {
        chip.selected = true;
        chip.color = 'primary';
      } else {
        chip.selected = false;
        chip.color = null;
      }
    });
}
Run Code Online (Sandbox Code Playgroud)