Angular *ngFor not displaying rows in striped format

I'm trying to create alternating row stripes using an *ngFor directive, but the CSS class is applying a gray background to all rows instead.

Here's what I've attempted:

HTML:

<div class="row ml-4" *ngIf="visible">
  <div class="divJanelaResultadoParcial" id="autocompletar" class="col-xl-9 divJanelaResultadoParcial">
    <a class="divJanelaProduto" *ngFor="let produto of produtos" [routerLink]="['/produtos', produto.id, produto.slug]" >
      <div class="row linhaProduto row-striped">

        <div class="col-3">
          <img class="img" src="{{ produto.foto_prin_1 }}"/>
        </div>

        <div class="col-6">
          <span class="ml-2">{{ produto.nome }}</span>
        </div>

        <div class="col-3">
          <span class="ml-2">{{ produto.preco | currency:'BRL' }}</span>
        </div>

      </div>
    </a>
  </div>
</div>

CSS:

.img {
        width:60px;
        height: 60px;
    }

    .divJanelaResultadoParcial{
        z-index: 20;
    }

    .linhaProduto{
        display: flex;
        align-items: center;
    }


    .row-striped:nth-of-type(odd){
        background-color: #efefef;
      }

      .row-striped:nth-of-type(even){
        background-color: #ffffff;
      }

This is the desired outcome:

https://i.sstatic.net/zJMIx.png

Answer №1

If you want to alternate the styling of items in a list, you can utilize the even and odd functionality provided by ngFor.

*ngFor="let product of products; let even = even; let odd = odd"


<div class="row ml-4" *ngIf="visible">
  <div class="partialResultWindow" id="autocomplete" class="col-xl-9 partialResultWindow">
    <a class="productWindow" *ngFor="let product of products; let even = even; let odd = odd" [routerLink]="['/products', product.id, product.slug]">
      <div class="row productRow row-striped" [ngClass]="{ odd: odd, even: even }">

        <div class="col-3">
          <img class="image" src="{{ product.main_photo }}"/>
        </div>

        <div class="col-6">
          <span class="ml-2">{{ product.name }}</span>
        </div>

        <div class="col-3">
          <span class="ml-2">{{ product.price | currency:'BRL' }}</span>
        </div>

      </div>
    </a>
  </div>
</div>
.row-striped.even {
  background-color: #ffffff;
}

.row-striped.odd {
  background-color: #efefef;
}

Answer №2

When using *ngFor, keep in mind that it is more for looping rather than identifying items.

If you want to create a striped effect, consider the following approach:

HTML:

<li *ngFor="let item of [1,2,3,4,5,6]; let odd = odd">
    <p [class.odd]="odd">item</p>
</li>

CSS:

.odd{
  background:grey
}

Check out the live demo here!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Adjusting the size of a Checkbox with CSS

Adjust the width of the checkbox for the call field to 25 pixels, ensuring it is displayed only when the left margin is clear. I'm having trouble figuring this out, even though it's probably something simple again. I double-checked that my style ...

``When clicked, the button vanishes into thin air

I have a basic HTML file (it's part of an MVC 4 project, but I also tested it on a simple HTML file) with two buttons and some jquery script: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"& ...

What steps should I take to successfully implement a post request from my Express server on my domain?

Within my component.ts file, I have a method that sends an HTTP request to my Express server to deliver the contents of an email. The issue arises when attempting this post request from my local machine versus deploying to a Digital Ocean server. I am un ...

The process of displaying video information on web browsers by streaming platforms

https://i.sstatic.net/XgnsX.png I recently noticed a feature in Chrome where there is a tab next to the extensions that shows videos playing in the browser. This tab only appears when a song or video is being played. For example, when I start a video on Y ...

Where should the transformation of server response data into a format that the component can interpret be done within the NgRx framework?

New to NgRx and feeling a bit confused at the moment. I have a basic component that displays a list of objects, in this case Orders, retrieved from the backend using an Effect. The challenge is to transform the response from the backend into a simplified l ...

Sending Pictures to a .NET Server using C#

As a newcomer to .NET, I have been conducting numerous tests and have encountered a problem that I hope someone can help me with. My goal is to enable users to upload a photo and save it to a specific path. While researching on MSDN, I came across informat ...

What is the best way to obtain a reference to the DOM elements that are bound with data from a webapi?

Currently, I am exploring the integration of Muuri into my application from this repository: https://github.com/haltu/muuri. My aim is to showcase data obtained from a web API using Muuri, which operates based on DOM items. So far, I have successfully disp ...

Implementing an automatic logout feature based on the expiration timestamp of a JWT token

My goal is to have the application automatically log out based on an expiry token. Angular Client Code: login(credentials) { return this.http.post('http://something/api/login/', credentials) .map(response => { let res ...

Setting the height of a div tag in CSS/HTML5 to match the current height of the browser window

Is there a way to make the height of my div tag always equal to the height of the browser's window, so it adjusts automatically when the browser is resized? I have tried using .class { height: 100%; } But this doesn't work. I've learne ...

Is it possible to display all tabs simultaneously with jQuery for tabbed content?

I'm currently utilizing jQuery to organize my content into various tabs, and it's working perfectly for displaying a specific <div> when a tab is clicked. However, I'm now looking to add a button that can toggle the display of all tab ...

Ways to enable smooth scrolling feature in Safari

I attempted to implement smoothscroll using a polyfill by adding the following code to the bottom of my body tag: <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99a8486869d819a8a9b868585c ...

Concealing a DisplayFor component with the help of Jquery

Hey there, I currently have a 'td' element that appears like this <td style="font-weight:bold"> @Html.DisplayFor(x => x.Parts[i].QtyInItem, new { htmlAttributes = new { @class = "qtyInItem" } }) </td> A ...

What is the method for displaying an array in JavaScript?

When a user clicks the value 3 input box, three input boxes will appear where they can enter values. However, when trying to submit the array, no elements are printed and an error message "Element is not defined" appears. var arr = [0]; function get_va ...

Are there any alternatives to using quotation marks and apostrophes in writing?

I have a line of PHP code that displays page numbers automatically generated based on the content in a table. All the page numbers have the same color, but I want to highlight the current active page. I tried using a condition within the class attribute, b ...

Exploring Angular 2: Crafting your own unique annotations

Can you design a unique annotation in Angular 2? For instance, an annotation like @LoginRequired that verifies if a user is logged in before proceeding with the component. If the user is logged in, the component continues as usual. If not, it redirects t ...

What is the best way to ensure that the CSS padding for a button matches the width of the column consistently?

I have encountered an issue where I am unable to maintain consistent padding for a button relative to the column width. This is crucial for me because the button's background changes when a user hovers over it. However, using a fixed value for the but ...

The challenge of resizing images using Chrome Print CSS

I have a unique method for centering an oversized image within its container. Everything works flawlessly, except when attempting to print in Chrome (printing in FF and IE behaves as expected). In Chrome's print preview, the image does not resize at a ...

Is there a way to defer a for loop in Angular?

In my Angular project, I am working on a sorting visualizer using the chart.js bar chart. Currently, I am focusing on visualizing bubble sort and I want to incorporate a delay in each iteration of the inner loop. I assume you are familiar with the loop s ...

The Azure DevOps pipeline is indicating that the global CLI version is higher than the local version you have on

I'm currently facing an issue while trying to deploy an Angular front end to Azure pipeline from GitHub using yaml. The problem occurs during the npm build and install stage, with an error message stating 'Your global Angular CLI version (15.2.6) ...