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

时间:2019-05-12 09:42:45

标签: angular angular-material

我正在使用mat-chip过滤表,并且一切似乎都可以正常工作:

home.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>

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

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

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

chipColor(sector: string) {
  if (this.filteredSectors.includes(sector)) {
    return 'primary';
  }
  return 'basic';
}

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

大约有20个扇区,所以我猜这不是性能问题吗?我觉得这很烦人,而不是一种好的做法。但是我该如何改变呢?

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

home.html

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

home.ts

  @ViewChild(MatChipList) chipList: MatChipList;

获取带有ViewChild批注的chipList,然后遍历芯片并设置其颜色,但这不起作用。选择了第二个芯片后,第一个芯片再次变为白色。

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;
      }
    });
}

0 个答案:

没有答案
相关问题