简体   繁体   中英

How do I change the background color of every div clicked inside ngFor?

I currently have some custom filter chips inside an ngFor and currently I have them set up to allow only one chip at a time to change background color when you click it. I want to change this so that I can select multiple chips and have multiple of them change background color when they are selected. How should I approach this?

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>

Component:

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

Try the below code.

 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" >

You can change active to be an array of numbers that would track all selected categories . Then you can check with active.includes(i) if the category is selected.

TypeScript file:

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 file:

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

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM