1
votes

I have a dynamically generated table using ngFor in angular2 and I want to colour even rows differently from odd rows.

    <div *ngIf="AreThereMyOldMessages">
      <div *ngFor="let oldm of MyOldMessages;let i of MyOldMessages.length">
        <tr>
          <td>{{i}}<br>
            {{oldm.text}}
          </td>
        </tr>
      </div>
    </div>
    <div *ngIf="AreThereMyNewMessages">
      <div *ngFor="let message of MyNewMessages;let i of MyNewMessages.length">
        <tr>
          <td>{{i}}<br>
            {{message.text}}
          </td>
        </tr>
      </div>
    </div>
  </table>

I want to colour each rows alternatively but this code prints all the rows in same colour. I have set a CSS file which colours each row accordingly using

table tr:nth-child(odd) td

this code.

2

2 Answers

4
votes

tr:nth-child(odd) will match table row elements that are an odd child. In your markup, each tr is indeed an odd child (first) of its parent div.

You would either need to change the markup or apply the css style to its parent div.

<table>
  <tbody>
    <ng-container *ngIf="AreThereMyOldMessages">
      <tr *ngFor="let oldm of MyOldMessages;let i of MyOldMessages.length">
      </tr>
    </ng-container>
    <ng-container *ngIf="AreThereMyNewMessages">
      <tr *ngFor="let message of MyNewMessages;let i of MyNewMessages.length">
      </tr>
    </ng-container>
  </tbody>
</table>
0
votes

Try the following CSS:

table tr:nth-child(even){
          background-color:red;
          }

table tr:nth-child(odd){
          background-color:black;
          }