How to make a flexbox in a div to have 2 columns with ngFor of mat-chips/angular material2? How to make a flexbox in a div to have 2 columns with ngFor of mat-chips/angular material2? angular angular

How to make a flexbox in a div to have 2 columns with ngFor of mat-chips/angular material2?


I am assuming that the table code you gave as an example is wrong, since you mentionned that you want 2 columns with 5 rows, which is equivalent to this. The answer below is to have a display similar to the table here

<table><tr><td>Fruit 1</td><td>Fruit 6</td></tr><tr><td>Fruit 2</td><td>Fruit 7</td></tr><tr><td>Fruit 3</td><td>Fruit 8</td></tr><tr><td>Fruit 4</td><td>Fruit 9</td></tr><tr><td>Fruit 5</td><td>Fruit 10</td></tr></table>

If you want to use flex, you need to set flow-direction to column and have a max-height on the container, equal to 5 times the height of a row

scss

$rowHeight: 40px;.flexp {    display: flex;    flex-wrap:wrap;    flex-direction: column;    max-height: calc(5 * #{$rowHeight});}.flexc {    height: $rowHeight;    flex-grow: 1;    display: inline-block;}

html

<mat-chip-list>    <div class="flexp">     <div class="flexc" *ngFor="let fruit of fruits">        <mat-chip>          {{fruit.typeOfFruit}}        </mat-chip>        {{fruit.name}}      </div>    </div></mat-chip-list>

Other solution not using flex

You can use the column-count property

scss

$rowHeight: 40px;.fruitContainer {    column-count: 2;    max-height: calc(5 * #{$rowHeight});}.fruit {    height: $rowHeight;}

html

<mat-chip-list>    <div class="fruitContainer">     <div class="fruit" *ngFor="let fruit of fruits">        <mat-chip>            {{fruit.typeOfFruit}}                    </mat-chip>                    {{fruit.name}}    </div></div></mat-chip-list>

Stackblitz demo

Below is the result

illustration


MatGridList is provided for this very reason.

<mat-grid-list cols="2" rowHeight="48px">    <mat-grid-tile *ngFor="let fruit of fruits">        <div class="flexc">            <mat-chip>                {{fruit.typeOfFruit}}            </mat-chip>            {{fruit.name}}        </div>    </mat-grid-tile></mat-grid-list>

See stackblitz example.


You can use CSS columns to define adaptive column layouts within a containing element. For example...

#container {    -webkit-columns: 2 200px;    -moz-columns: 2 200px;    columns: 2 200px;}

The first value (2) declares the number of columns and the second value (200px) declares their minimum width, such that the browser will collapse the columns if the container isn't wide enough. Vendor prefixing might not be strictly necessary but is still recommended.

See this CSS-Tricks post, which also deals with column gutters etc, for more info.

:)