Jack23
Jack23

Reputation: 1396

Angular - Display *ngFor in Row and Column

I'm learning to use Angular and I have a problem with how to show data in columns.

In my app.components.ts I have:

<div class="cardComp" *ngFor="let person of people">
  <app-card-person [person]="person"></app-card-person>
</div>

// people is an array of objects 

In my card-person.component.ts

<div class="card" style="width: 18rem;">
    <!-- <img src="..." class="card-img-top" alt="..."> -->
    <div class="card-body">
        <h5 class="card-title">{{person?.name}} {{person?.surname}}</h5>
        <p class="card-text">{{person?.description}}</p>
        <!-- <a href="#" class="btn btn-primary">Go somewhere</a> -->
    </div>
</div>

In this way, I obtain a list of cards but they are 1 per row:

CARD1
CARD2
CARD3
.....

What I would to obtain is:

CARD1                        CARD2
CARD3                        CARD4
.....                        .....

Upvotes: 1

Views: 2925

Answers (2)

Kent Wynn
Kent Wynn

Reputation: 11

CSS Grid

In your app.component.scss

.cardComp {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px; // gap between columns
}

Upvotes: 1

Yong Shun
Yong Shun

Reputation: 51125

Solution 1: Work with flexbox

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 50%;
}
<div class="container">
  <div class="cardComp item" *ngFor="let person of people">
    <app-card-person [person]="person"></app-card-person>
  </div>
</div>

Result

Sample Solution 1 on StackBlitz

Recommended to read this Flexbox article.


Solution 2: Work with Bootstrap

Pre-requisites: Import Bootstrap CSS file.

<div class="row">
  <div class="cardComp col-6" *ngFor="let person of people">
    <app-card-person [person]="person"></app-card-person>
  </div>
</div>

Result

Sample Solution 2 on StackBlitz

Upvotes: 2

Related Questions