Vertically align Ionic cards with Angular directives

Viewed 1067

I'm trying to do a simple card collection using Ionic framework.

I'm using SpaceX API to populate the cards. My code include angular directives. I built this:

<ion-grid>
  <ion-row>
    <ion-col col-4>
      <ion-card *ngFor="let launch of list_launches">
        <ion-card-header>
          {{ launch.mission_name }}
        </ion-card-header>
        <ion-card-content>
          <ion-thumbnail item-start>
            <img src="{{launch.links.mission_patch_small}}">
          </ion-thumbnail>
        </ion-card-content>
      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

this *ngFor="let launch of list_launches" is used to get some atributes from object list_launches.

My Solution

I found this solution:

<ion-row>
    <ion-col col-4>
      Left
    </ion-col>
    <ion-col col-4>
      Middle
    </ion-col>
    <ion-col col-4>
      Right
    </ion-col>
 </ion-row>

but this does not work properlly when i use the *ngfor parameter. Want to vertically align this Ionic cards .

1 Answers

So the issue here is that Ionic grid expects a non-generic template to build more complex grids. I always found these layout components to be overkill, since most stuff can be done with just a few CSS declarations. In your case I would not use the ionic grid at all and write it in CSS Grid. Two simple CSS rules can deal with this:

display: grid;
grid-template-columns: 1fr 1fr 1fr;

I am creating a very basic grid here and tell it that it has three equally sized columns (1fr means 1 fraction).

You could also use the repeat function

display: grid;
grid-template-columns: repeat(3, 1fr);

Also much less code:

<div style="display: grid;grid-template-columns: 1fr 1fr 1fr;">
  <ion-card  *ngFor="let launch of list_launches">
    <ion-card-header>
      {{ launch.mission_name }}
    </ion-card-header>
    <ion-card-content>
      <ion-thumbnail item-start>
        <img src="">
      </ion-thumbnail>
    </ion-card-content>
  </ion-card>
</div>

The result

https://stackblitz.com/edit/ionic-7qd5xf

Update: As Thomas suggested in the comments it is also sufficient to use the *ngFor directive on the ion-col itself:

<ion-row>
  <ion-col col-4 *ngFor="let launch of list_launches" >
    <ion-card >
      <ion-card-header>
        {{ launch.mission_name }}
      </ion-card-header>
      <ion-card-content>
        <ion-thumbnail item-start>
          <img src="">
        </ion-thumbnail>
      </ion-card-content>
    </ion-card>
  </ion-col>
</ion-row>
Related