0

I have a 'masonry' like grid on my website, which I display using *ngFor. The grid blocks looks like the follow:

T T T
S A S
T S T

where T - stands for Tall blocks, S - short blocks, A - special section with a tall blocks height.

I'm trying to create a a grid which will be automatically populated using ngFor but using the grid schema.

For example:

T T T
S T S
T S T

and continue following the format ->

T T T
S T S
T S T
T T T
S T S
T S T
T T T
S T S
T S T

and so on, using the first three rows as an example, tall or short blocks specified by class only. So my questions is, which is the best way to check all this conditions in order to display them in the following format?

d123546
  • 249
  • 4
  • 16

1 Answers1

1

To get the effect you want, you will need to leverage css to create a masonry layout.

The best way is to use css column-count, but you will need to transpose your array so that each row of your data represents a column.

This example utilises ngClass to provide an object where the keys are CSS classes that get added when the expression given in the value evaluates to true.

masonry.component.ts

export class MasonryComponent {
    wall = [['T', 'T', 'T'], ['S', 'A', 'S'], ['T', 'S', 'T']];

    constructor() { }

    transpose(arr: any[]){
        return arr.map((col, i) => arr.map((row)  => row[i] ));
    }
}

masonry.html

<div class="wall" >
    <ng-container *ngFor="let blockCol of transpose(wall)">
        <div *ngFor="let block of blockCol" class="block" [ngClass]="{ 
            'tall' : block === 'T', 
            'short': block === 'S', 
            'special': block === 'A'  }">{{ block }}</div>
    </ng-container>
</div>

masonry.css

.wall {
    width: 170px;
    column-count: 3;
}

.block {
    width: 50px;
    border: 1px solid black;
}

.tall {     height: 50px; }
.special {  height: 50px; }
.short {    height: 25px; }
Community
  • 1
  • 1
Christopher Moore
  • 3,071
  • 4
  • 30
  • 46