Search code examples
csscss-grid

Css grid and ngRepeat


I have a grid layout that is not working correctly with ngFor (or any other loop) If I place class="container" on the ngFor div it creates two containers, if I place it in an outer div it doesn't work. How can I create a grid layout for a repeatable list?

  <div class="container">
      <div *ngFor="let house of array;let index=index;">
        <div class="item row2 col1">
          1<img src="assets/house-pic4.jpg" class="grid-image">
        </div>

        <div class="item row2 col2" *ngIf="index %2 == 0">
          2<img src="assets/house-pic2.jpg" class="grid-image">
        </div>

        <div class="item row2 col1" *ngIf="index %2 != 0">
          3<img src="assets/house-pic2.jpg" class="grid-image">
        </div>

        <div class="item row2 col2">
          4 <img src="assets/house-pic3.jpg" class="grid-image">
        </div>
      </div>
    </div>

css:

    .container {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    grid-auto-rows: 12vh;
    grid-auto-flow: dense;
    }

    .item {
    display: block;
    overflow: hidden;
    writing-mode: horizontal-tb;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 0px;
    }

    .row2 {
    grid-row-end: span 2;
    }

    .row3 {
    grid-row-end: span 3;
    }

    .row4 {
    grid-row-end: span 4;
    }

    .row5 {
    grid-row-end: span 5;
    }

    .row6 {
    grid-row-end: span 6;
    }

    .col2 {
    grid-column-end: span 2;
    }

    .col3 {
    grid-column-end: span 3;
    }

Solution

  • Is this more of what you are looking for? I replaced the looped div with an ng-container so it doesn't show in the dom.

    <div class="container">
        <ng-container *ngFor="let house of array;let index=index;">
            <div class="item row2 col1">
                1<img src="assets/house-pic4.jpg" class="grid-image">
            </div>
    
                <div class="item row2 col2" *ngIf="index %2 == 0">
                    2<img src="assets/house-pic2.jpg" class="grid-image">
            </div>
    
                    <div class="item row2 col1" *ngIf="index %2 != 0">
                        3<img src="assets/house-pic2.jpg" class="grid-image">
            </div>
    
                        <div class="item row2 col2">
                            4 <img src="assets/house-pic3.jpg" class="grid-image">
            </div>
        </ng-container>
    </div>
    

    Another option is to set that looped div to display: contents so that they are ignored for the purpose of rendering. stackblitz

        <div class="contents" *ngFor="let house of array;let index=index;">
    
    .contents {
      display: contents;
    }