ngFor: different color for odd/even rows when loop is in ng-container
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?
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;
}
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
You can also use in this way:
<ng-container *ngFor="let detail of data.details; let odd = odd">
<tr [class.oddBackground]=" 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>
This will add oddBackground class only if the row is odd which means odd variable is true.
UPDATE (for latest Angular versions):
You can implement it like this:
odd as isOdd; even as isEven;"
<ng-container *ngFor="let detail of data.details; odd as isOdd; even as isEven;">
<tr [ngClass]="{ 'odd': isOdd, 'even': isEven }"> // Or 'k-alt': isOdd
...
</tr>
</ng-container>
Attached herewith is a Stackblitz Demo for your reference.
You can also visit the NgForOf Documentation where it also supports e.g first, last, and count