[英]How do I change the background color of every div clicked inside ngFor?
我目前在 ngFor 中有一些自定义过滤器芯片,目前我将它们设置为一次只允许一个芯片在您单击它时更改背景颜色。 我想改变它,以便我可以 select 多个芯片,并让其中多个芯片在被选中时更改背景颜色。 我应该如何处理这个?
HTML:
<div *ngFor="let category of categories; let i = index" class=" filter-chips px-3"
(click)="active = i; chipAdded(category)" [ngClass]="active === i ? 'chip-clicked': '' ">
{{category}}
</div>
零件:
active: any;
CSS:
.filter-chips {
min-width: 50px;
height: 30px;
background-color: grey;
border: 1px solid $grey-04;
box-sizing: border-box;
border-radius: 24px;
text-align: center;
color: $grey-02 !important;
cursor: pointer;
}
.chip-clicked {
background-color: green;
color: white !important;
border-color: white !important;
}
试试下面的代码。
onChildSelect(Child) { for (let myChild of this.children) { myChild.BackgroundColour = "white"; } Child.BackgroundColour = "red"; }
<li style="cursor: pointer" class="list-group-item" *ngFor="let Child of children" (click)="onChildSelect(Child)" [style.background-color]="Child.BackgroundColour" >
您可以将active
更改为跟踪所有选定categories
的数字数组。 然后,您可以使用active.includes(i)
检查是否选择了category
。
TypeScript 文件:
public categories = ['Category 1', 'Category 2', 'Category 3'];
public active: number[] = [];
chipAdded(index: number): void {
if (this.active.includes(index)) {
this.active = this.active.filter((item) => item !== index);
} else {
this.active.push(index);
}
}
HTML 文件:
<div *ngFor="let category of categories; let i = index" class="filter-chips px-3"
(click)="category.active = true; chipAdded(category)" [ngClass]="category && category.active ? 'chip-clicked': '' ">
{{category}}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.