添加一个特定的 css class 到第一个元素然后休眠接下来的两个元素等一个在 Angular 和 flex 中使用 ngFor

add a specific css class to the two first elment then skeep the next two element and so one using ngFor in Angular and flex

我有这段代码,用于显示产品列表,在 Angular:

中使用 *ngFor
<div class="container-products">
  <div class="item-product" *ngFor="let product of ['product A', 'product B', 'product C', 'product D']; let index = index">
    <div [ngClass]="{'color-gray': index % 2 === 0}">{{ product }}</div>
  </div>
 </div>

用这个 CSS:

  .container-products{ 
        display: flex;
        flex-wrap: wrap;
     }
     .item-product{
        flex: 50%;
     }
     .color-gray {
        background-color: gray;
     }

我得到的结果是这样的: my table with color gray 我的问题是我可以在 html 中放置什么来代替索引 % 2 === 0 以使第一个灰色的两个保持下一个,等等。 谢谢。

只用CSS和nth-child就可以得到预期的样式:

div.item-product:nth-child(4n-3),
div.item-product:nth-child(4n-2) {
    background-color: gray;
}

这样你就可以将 4 个元素组成一组,然后取:

  • 第 4 个元素减 3(因此是 4 组中的第一个)
  • 第 4 个元素减去 2(所以 4 组中的第 2 个)

使用您自己的代码的示例(为清楚起见,删除了 angular):

.container-products {
  display: flex;
  flex-wrap: wrap;
}

.item-product {
  flex: 50%;
}

div.item-product:nth-child(4n-3),
div.item-product:nth-child(4n-2) {
  background-color: gray;
}
<div class="container-products">
  <div class="item-product">
    <div>Product A</div>
  </div>
  <div class="item-product">
    <div>Product B</div>
  </div>
  <div class="item-product">
    <div>Product C</div>
  </div>
  <div class="item-product">
    <div>Product D</div>
  </div>
  <div class="item-product">
    <div>Product E</div>
  </div>
  <div class="item-product">
    <div>Product F</div>
  </div>
  <div class="item-product">
    <div>Product G</div>
  </div>
  <div class="item-product">
    <div>Product H</div>
  </div>
</div>