I have a table in which I'd like to give the odd and even rows a different background color. Normally, you can use the odd
and even
variables for this. However, I'm now building up my table rows inside an ng-container
so I can conditionally create one or more rows per iteration. In this case, every iteration creates 1 or 2 rows, depending on a variable.
<ng-container *ngFor="let detailof data.details; let odd = odd;">
<tr [ngClass]="{ 'k-alt': odd}">
<td>
{{ detail.number1 }}
</td>
<td>
{{ detail.number2 }}
</td>
<td>
{{ detail.number3 }}
</td>
</tr>
<tr *ngIf="detail.conditionalVariable" [ngClass]="{ 'k-alt': odd}">
<td></td>
<td>{{ detail.conditionalVariable }}</td>
<td></td>
</tr>
</ng-container>
As you can see, every iteration will cause the rows to be marked with a different background and not every row itself because the odd variable is declared in the *ngFor
in the ng-container
element.
Is there a way to give each row a different background color when using ng-container
with conditional rows?
You can use the index property:
<ng-container *ngFor="let detailof data.details; let index = index" [ngClass]="{'myStyle': 0 === index % 2}">...</ng-container>
ngForOF Official docs
Why don't you use CSS for this? For example, set k-alt
class for all of your rows and in your CSS:
tr.k-alt:nth-child(odd) {
background: #CCC;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With