Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngFor: different color for odd/even rows when loop is in ng-container

Tags:

angular

ngfor

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?

like image 435
Bv202 Avatar asked Jan 25 '18 09:01

Bv202


2 Answers

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

like image 148
axl-code Avatar answered Nov 07 '22 06:11

axl-code


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;
}
like image 16
Roland Rácz Avatar answered Nov 07 '22 05:11

Roland Rácz