【问题标题】:How do I change the background color of every div clicked inside ngFor?如何更改在 ngFor 中单击的每个 div 的背景颜色?
【发布时间】:2022-01-23 09:24:24
【问题描述】:

我目前在 ngFor 中有一些自定义过滤器芯片,目前我将它们设置为一次只允许一个芯片在您单击它时更改背景颜色。我想更改此设置,以便我可以选择多个芯片并让其中多个芯片在选择时更改背景颜色。我应该如何处理?

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

【问题讨论】:

    标签: javascript html css angular typescript


    【解决方案1】:

    试试下面的代码。

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

    【讨论】:

      【解决方案2】:

      您可以将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>
      

      Working example

      【讨论】:

        猜你喜欢
        • 2014-05-09
        • 2017-05-20
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 2012-06-09
        • 2022-11-22
        • 1970-01-01
        相关资源
        最近更新 更多