Home > Software design >  How do I change the background color of every div clicked inside ngFor?
How do I change the background color of every div clicked inside ngFor?

Time:12-22

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

CodePudding user response:

Try the below code.

onChildSelect(Child)
{
    for (let myChild of this.children) {
        myChild.BackgroundColour = "white";
    }

    Child.BackgroundColour = "red";
}
<li style="cursor: pointer"  
    *ngFor="let Child of children" (click)="onChildSelect(Child)" 
    [style.background-color]="Child.BackgroundColour" >

CodePudding user response:

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" 
  (click)="category.active = true; chipAdded(category)" [ngClass]="category && category.active ? 'chip-clicked': '' ">
    {{category}}
</div>

Working example

  • Related