Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate column order using ngFor

How can I alternate the order of the columns for each row using ngFor?

For example here the image will always be on the right. How can I do so that in each row I alternate and the image shows one on the left and one on the right and so on?

<div class="row" *ngFor="let servicio of servicios">
  <div class="col-lg-5">
    {{ servicio.titulo }}
  </div>
  <div class="col-lg-7">
    <img src="{{ servicio.imagen }}" alt="">
  </div>
</div>
like image 507
Paco Zevallos Avatar asked Feb 04 '26 15:02

Paco Zevallos


1 Answers

You can use the local variables available, for example even and odd, in *ngFor to alternate the order of the columns with two ngIf directives. One of them makes titulo the first column for rows with an even index, the other one makes it the last column for rows with an odd index.

<div class="row" *ngFor="let servicio of servicios; let even=even">
  <div *ngIf="even" class="col-lg-5">
    {{ servicio.titulo }}
  </div>
  <div class="col-lg-7">
    <img src="{{ servicio.imagen }}" alt="">
  </div>
  <div *ngIf="!even" class="col-lg-5">
    {{ servicio.titulo }}
  </div>
</div>

See this stackblitz for a demo.

like image 179
ConnorsFan Avatar answered Feb 06 '26 07:02

ConnorsFan