Make every odd row different color than even row – Angular and CSS

Issue

I want to make every other row different color. I am not sure what I am doing wrong, as it looks like it should work, but it colors me EVERY row with grey.

I am using angular, and I have parent and child component
In my parent component I pass the data to the child component.

HTML is

 <div class="list-view">
      <div *ngFor="let event of allEvents">
        <app-event-item
          [eventsList]="event"
        ></app-event-item>
      </div>
    </div>

And my CSS code of parent component

 .list-view {
      display: flex;
      flex-direction: column;
    }

Now in child component I get multiple arrays of event with data, which i passed to child component and loop through data with *ngFor

In html then I just display the rows of data.

HTML code of child component:

  <div class="list-view">
    <img [src]="imageUrl" />
    <div class="about">
      <h4>
        <a>{{ eventsList.title }}</a>
      </h4>
    </div>
    <div class="date">
      <p>{{ eventsList.date }}</p>
    </div>
    <div class="count">
      <p>{{ eventsList.count }}</p>
    </div>
</div>

Here is my css code in CHILD component

 .list-view {
    display: grid;
    grid-template-columns: 300px 45% 1fr 1fr;
    align-items: center;
    height: 100px;

    &:nth-child(odd) {
      background-color: #F9F9F9;
    }

    img {
      max-height: 100%;
      max-width: 100%;
      object-fit: cover;
      border-radius: 0.75rem;
    }

    .about-event {
      padding-left: 1rem;
    }
  }

It makes every row color #F9F9F9.

Solution

you can use an Angular aproach:

<div class="list-view">
      <div *ngFor="let event of allEvents;let odd=odd" 
             [style.background-color]="odd?'red':null>
        <app-event-item
          [eventsList]="event"
        ></app-event-item>
      </div>
</div>

Answered By – Eliseo

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.