Search code examples
angularngformat-card

How to use ngFor to make cards remain in a row in Angular 6?


ngFor generated card stacked on each other instead of remain in a row.

I am generating cards through ngFor. I am using fxFlex="30" for each card but they stacked on each other. I used flex-wrap also but didn't work.

<div fxFlex *ngIf="designs" [@expand]>
  <div fxLayout="column" fxLayout.gt-sm="row" style="display: inline" *ngFor="let design of designs">
    <div fxFlex="30">
      <mat-card>
        <mat-card-header>
          <mat-card-title>
            <h2>{{design.label}}</h2>
          </mat-card-title>
          <mat-card-subtitle>
            <h3>{{design.time}}hr</h3>
          </mat-card-subtitle>
        </mat-card-header>
        <img mat-card-image src="{{BaseURL + design.image}}">
        <mat-card-content>
          <p>{{design.description}}</p>
        </mat-card-content>
        <mat-card-actions style="margin: auto;">
          <button mat-stroked-button routerLink="/contact" color="primary">Book Now</button>
        </mat-card-actions>
      </mat-card>
    </div>
  </div>
</div>

I want my generated cards should be in a row. But in actual they stacked on each other.


Solution

  • It's important to pay attention to the minor details on the Angular flex layout page. This kind of thing got me a few times when starting out since I wasn't as familiar with flex before using it.

    Using fxLayout mostly tells the element what kind of container it's going to be. In this case, you probably want to move your *ngFor to the same div that has the fxFlex="30", and with luck, you might be able to move them both to the card.

    <div fxFlex *ngIf="designs" [@expand]>
      <div fxLayout="column" fxLayout.gt-sm="row" style="display: inline">
        <div fxFlex="30" *ngFor="let design of designs">
    

    Depending on what you need this for, a Grid might help a lot as well.