How to add a div after every 3 elements in *ngFor
Asked Answered
F

2

5

I am trying to build an angular project . In my project I want to show a list of books ,I have a SmallBookView Component for a single book and I want to use ngFor to show many other books./ however after every 3 books I need to add a div to separate this books, In the end it should look like so

<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<div class="clearfix"> </div>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<div class="clearfix"> </div>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<div class="clearfix"> </div>

the div separate each line of books in the ui. I am trying to use ngFor like so

<app-small-book-view *ngFor="let i of [1,2,3,4,5,6,7]; let _i = index">
  <div class="clearfix" *ngIf="(_i % 3) == 0"></div>
</app-small-book-view>

but this is adding the div only inside the SmallBookView instead of between them, how do I add this div between the components>

Falk answered 14/8, 2018 at 21:27 Comment(0)
F
13

You can use ng-container to group multiple components without the container rendering.

<ng-container *ngFor="let i of [1,2,3,4,5,6,7]; let _i = index">
  <app-small-book-view></app-small-book-view>
  <div class="clearfix" *ngIf="(_i % 3) == 0"></div>
</ng-container>
Fairing answered 14/8, 2018 at 21:30 Comment(1)
This answers the question, but it is worth noting that *ngIf="(_i % 3) == 0" will create a div after the first app-small-book-view and after every third element afterwards instead of after the third app-small-book-view as is what is desired. This is because the indexing is zero-based and (0 % 3) == 0. You might want *ngIf="(_i % 3) == 2" instead to add a div after every third element.Novelty
H
6

This should not be a task for script but rather for CSS:

app-small-book-view:nth-child(3n)::after {
    /*the clearfix thing*/
    content: ""; 
    clear: both;
    display: table;
}

So your markup will be just linear sequence of children:

<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
<app-small-book-view></app-small-book-view>
Heartworm answered 14/8, 2018 at 21:33 Comment(2)
You could also do this via CSS gridFairing
Yeah. Anything but not use of script for layout purposes.Heartworm

© 2022 - 2024 — McMap. All rights reserved.