Home > Back-end >  How to order the content generated by *NgFor in rows and columns (FlexLayout) Angular
How to order the content generated by *NgFor in rows and columns (FlexLayout) Angular

Time:10-08

I am trying to get the elements generated by *NgFor to be sorted into 3 elements per row.

Currently this code puts all the content of "cont" in a single row.

<div fxLayout="row">
 <mat-card  *ngFor="let item of cont">
  <p>{{item.title}}</p>
 </mat-card>
</div>

but I would like to have something like:

item.title1 item.title2 item.title3

item.title4 item.title5 item.title6

CodePudding user response:

Not sure if it would be of any help as I see you are asking with flex layout, but what if you use display grid to achieve that.

You would have something like:

<div >
 <mat-card  *ngFor="let item of cont">
  <p>{{item.title}}</p>
 </mat-card>
</div>

And in your css you can have

.grid{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

That way you will always have 3 elements per row

Example: https://stackblitz.com/edit/angular-ivy-s5swyy?file=src/app/app.component.html,src/app/app.component.ts,src/app/app.module.ts,package.json,src/app/app.component.css

CodePudding user response:

Well, you can do something like this.

Give your parent div a width of 100% and then give your mat-cards widths of 33.3% each & and then give your flex div (parent-div) the flex-wrap property which will allow every 4th mat-card to shift to another line.

<div >
   <mat-card *ngFor="let item of cont" >
      <p>{{item}}</p>
   </mat-card>
</div>
.w-33 {
width: 33.3%;
}
  • Related