Create a new template for each N *ngFor elements

Asked

Viewed 152 times

5

Hello, I have an array items:any[] and I want to iterate in the view with the *ngfor, however, I am using a template <carousel> where for every item of that slide I call <carousel-item>, Today my code follows this hierarchy:

<carousel>
  <carousel-item>
    <div *ngFor="let item of items">
      {{item.nome}}
    </div>
  </carousel-item>
  <carousel-item>
    <!-- outro conteúdo -->
  </carousel-item>
</carousel>

With this code I have the following result, note that item 5 ends up exceeding the div:

inserir a descrição da imagem aqui

My doubt: I want every 4 elements of the items create a new template <carousel-item>, in order to stay that way:

inserir a descrição da imagem aqui

I wonder if you can solve my problem using only the iteration of *ngFor and some *ngIf or modifying something in the hierarchy, but I have no idea how to solve without harming the performance of the application.

Thanks in advance.

  • I had a similar problem but could only calling a function in ngFor which returns an array of arrays, with sub arrays with a maximum of 4 items, so I used two loops

1 answer

1


You have to split turn your item array to a Matrix Example:

['a', 'b', 'c', 'd', 'e'];

should turn

[ ['a', 'b', 'c', 'd'], ['e'] ];

After transforming your array into an array, you can add an ngFor to your Carousel-item, example:

// seu-component.ts
chunkItems: any = [];

ngOnInit() {
    this.chunkItems();
}

/** Transforma seu array de items em chunks **/
chunkItems() {
    this.chunkItems = [];
    const numberOfItemsPerRow = 4;
    for(let i = 0; i < this.items.length; i += numberOfItemsPerRow) {
        this.chunkItems.push(this.items.slice(i, i + numberOfItemsPerRow));
    }
}

// seu-component.html
<carousel>
  <carousel-item *ngFor="let chunkItem of chunkItems">
    <div *ngFor="let item of chunkItem">
      {{item.nome}}
    </div>
  </carousel-item>
</carousel>
  • Perfect, you just saved one day

Browser other questions tagged

You are not signed in. Login or sign up in order to post.