有一个定义
<mat-chip-list>
<mat-chip
*ngFor="let chip of chips"
[ngClass]="isActive(chip)"
(click)="setActiveChip(chip)">
{{ chip.name }}
</mat-chip>
</mat-chip-list>
具有isActive
功能,用于根据变量cardId
将芯片设置为活动状态:
isActive(chip) {
const cardId = 2;
if(cardId) {
const activeChip = chip.id === cardId;
return activeChip ? 'mat-chip-active' : '';
}
}
如何使用另一个(setActiveChip
)函数将ngClass设置为另一芯片?
答案 0 :(得分:1)
请参阅:
https://stackblitz.com/edit/set-active-chip-nvg8no
import { Component } from "@angular/core";
import { MatChipInputEvent } from "@angular/material";
@Component({
selector: "chips-overview-example",
templateUrl: "chips-overview-example.html",
styleUrls: ["chips-overview-example.css"]
})
export class ChipsOverviewExample {
chips = [
{ id: 1, name: "One" },
{ id: 2, name: "Two" },
{ id: 3, name: "Three" }
];
// Set default to the 2nd chip
activeChip = this.chips[1];
setActiveChip(chip) {
this.activeChip = chip;
}
}
HTML:
<mat-chip-list>
<mat-chip
*ngFor="let chip of chips"
[ngClass]="{'mat-chip-active': activeChip === chip}"
(click)="setActiveChip(chip)">
{{ chip.name }}
</mat-chip>
</mat-chip-list>