I want to render elements from an array using an ngFor loop. The array can be of different sizes.
I want that always 5 elements of an array make one row.
For example, if my array were of size seven:
Element Element Element Element Element
Element Element
Or of size 15:
Element Element Element Element Element
Element Element Element Element Element
Element Element Element Element Element
etc.
What kind of HTML elements is not relevant at first. I just want to understand how this could be implemented with ngFor (or several) in Angular.
>Solution :
You can achieve it using grid.
.grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 16px;
}
.grid > div {
border: 1px solid;
padding: 0px 8px;
box-sizing: border-box;
}
<div class="grid">
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Baz</div>
<div>Baz</div>
<div>Baz</div>
</div>
Or, if you want, you can achieve it using a flex layout:
.flex {
display: flex;
flex-flow: row wrap;
gap: 16px;
width: 100%;
}
.flex > div {
border: 1px solid;
flex: 0 1 calc(20% - 16px);
padding: 0px 8px;
box-sizing: border-box;
}
<div class="flex">
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Foo</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Bar</div>
<div>Baz</div>
<div>Baz</div>
<div>Baz</div>
</div>
Sidenote : using the flex approach you would have a much easier life when (and if) dealing with responsiveness. IE: you could add a flex-wrap: wrap and a min-width to the divs and let flex handle it.
On the other hand, if using the grid approach, you could simply add some @media and change how grid-template-columns render the items.
That’s up to you, but anyway both ways are valid.