I am using *ngFor
and it has me perplexed. I am trying to use UIkit but it would be applicable to Bootstrap also.
As the other answer proposed, storing the index
with something like *ngFor="let device of devices ; let i = index"
will let you keep track of the index in the collection you're iterating over.
Then, as far as I understand you need correctly, you want to conditionally apply a class
to elements, namely the first and every third. If you actually want a series like T,F,F,T,F,F,T,F,F,T,...
then you can use i % 3 === 0
to produce it and apply a class
conditionally with something like
<div (class)="i % 3 === 0 ? 'class-to-apply' : ''">
This will let you conditionally add a class to the first and every third element afterwards.
If instead you want to have different html based on the index, then you have to use ngIf
branching and have two html snippets to handle the two cases. Something in the lines of:
<div *ngIf="i % 3 === 0">first case</div>
<div *ngIf="i % 3 !== 0">second case</div>
Just use index
that directive provides
like
*ngFor="let device of devices ; let i = index"
then in the html just check with *ngIf
and add your block
like <div ... *ngIf="i % 3 === 0"></div>
Probaly you need this approach Ng-repeat-start in angular2 - aka repeat multiple elements using NgFor
(in AngularJS 1.x it was pair of directives ng-repeat-start
ng-repeat-end
, now it's another approach for the same)
@ChristopherMoore have great answer but you need to modifythe devices_triple function to add a statement to check
if (i == this.devices.length){
arr.push(triple);
}
this will help where cases like [[1, 2, 3],[4, 5]] and [[1, 2, 3],[4, 5, 6],[7]]
If you are using Bootstrap V4.0, below link is useful.
How to create a new row of cards using ngFor and bootstrap 4
In my case, it works for me as I am using Bootstrap V4.
Here's an aproach that utilises nested *ngFor
to force wrapping 3 items in a div
First you will need a getter
to split your array into threes.
get device_triples(){
let arr = [];
let triple= [];
for (let i = 1; i <= this.devices.length; i++) {
triple.push(this.devices[i - 1]);
if (i % 3 === 0) {
arr.push(triple);
triple= [];
}
}
if(triple.length > 0){
arr.push(triple);
}
return arr;
}
This function will transform:
[1, 2, 3, 4, 5, 6]
into [[1, 2, 3],[4, 5, 6]]
[1, 2, 3, 4, 5]
into [[1, 2, 3],[4, 5]]
You could also use _.chunk for this
Then you will need to iterate over the new array in your template, add your "div of threes" and then iterate over each sub array, each with at most 3 items in:
<div *ngFor="let triple of device_triples">
<div class="uk-child-width-expand@s uk-text-center" uk-grid>
<div *ngFor="let device of triple">
<h2 class="uk-h2">{{ device.name }}</h2>
...
<div>
</div>
</div>