Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a ngFor with a modulus operator in Angular 2

Tags:

html

angular

I'm writing out images to the web page. Every three images I would like to start a new row. Does angular 2 support this?

like image 295
Lockless Avatar asked Nov 29 '22 09:11

Lockless


2 Answers

You can achieve it by doing following:

<div *ngFor="let t of temp(math.ceil(arr.length/3)).fill(); let i = index" class="row">
  <div *ngFor="let item of arr.slice(3*i,3*i + 3);" class="item">
    {{item}}
  </div>
</div>

And in your component:

export class App {
  temp = Array;
  math = Math;
  arr= [1,2,3,4,5,6,7,8,9,10,11];
}

Here's working Plunker

like image 195
yurzui Avatar answered Dec 06 '22 13:12

yurzui


You can access the index of the iteration from the *ngFor like so:

*ngFor="let x of container; let i = index;"

you can then reference that index in an *ngIf inside of the *ngFor to display your new row:

<div *ngIf="i%3 === 0">

like image 35
Alex Wheeler Avatar answered Dec 06 '22 11:12

Alex Wheeler