angular 8 getting alternate color on rows that uses ngFor

Viewed 1337

I am running into issues in getting the alternate rows with 2 different colors. I have a JSON data coming from backend, which is a dynamic array of objects. I need to show the data in the table as in the example here: https://stackblitz.com/edit/create-xpkbjm?file=app/app.component.html

The odd, even rule that I find in most Stackoverflow questions doesn't seem to work here.

I would like to show the rows with alternate colors(the rows come as groups). The data should be presented similar to the link in the above stackblitz, but each rows should have alternate color. The odd, even rule only work for each group, but doesn't alternate the color in the table as a whole.

2 Answers

You can do this with plain old css,

tr:nth-child(2n) {
  background: lightgray;
}

You can update the object that you're using to loop over and create the table.

Currently, you're using two loops,

  • one over tbody with groups
  • and one over tr with group.events

Instead, you can create another variable that is a list of events,

// app.component.ts
events = this.groups.map(g => g.events).flat();

Which simplifies your HTML to,

<!-- app.component.html -->
<tr *ngFor="let event of events; index as i">
  <td>
    {{event.event}}
  </td>
</tr>

Check on stackblitz

UPDATE:

You can track total elements using a group/count property on each event across the whole object like so,

//app.component.ts
constructor() {
  this.createGroups();
}

createGroups() {
  let count = 0;
  this.groups.forEach(g => {
    g.events.forEach(e => {
      e.group = count++;
    });
  });

  console.log(this.groups);
}

And then use [ngClass] to bind a css class based on this property,

<tbody>
  <tr *ngFor="let group of groups; index as i">
    <table>
      <tbody>
        <tr *ngIf="i!==0">
          <td></td>
        </tr>
        <tr *ngFor="let event of group.events;" [ngClass]="{'even': event.group % 2 !== 0}">
          <td>{{event.event}} {{event.group}}</td>
        </tr>
      </tbody>
    </table>
  </tr>
</tbody>

Updated stackblitz

You can do this using pure CSS without the need to modify the angular.

tbody tr
{
  background-color: #FFFFFF;
  color: #fff;
}

tbody tr:nth-child(odd)
{
  background-color: #000000;
  color: #fff;
}
Related