我有這段代碼,用于顯示產品串列,在 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;
}
我的結果是這樣的: 我的表格顏色為灰色 我的問題是我可以在 html 中放置什么 index % 2 === 0 以使前兩個灰色保持兩個下一個等一個。謝謝你。
uj5u.com熱心網友回復:
您可以僅使用 CSS 和nth-child獲得預期的樣式:
div.item-product:nth-child(4n-3),
div.item-product:nth-child(4n-2) {
background-color: gray;
}
有了這個,你正在制作 4 個元素的組,然后采取:
- 第 4 個元素減去 3(因此是 4 組中的第 1 個)
- 第 4 個元素減 2(所以 4 組中的第 2 個)
使用您自己的代碼的示例(為清楚起見洗掉了角度):
.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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479668.html
下一篇:Angular13ReactiveFormValidationParserError:Unexpectedtoken[,expectedidentifierorkeyword
