Scrolling through the list twice with * ngFor
I have a list of tasks that I want to display in <ion-row>
. Each line can contain no more than two tasks. Each task is certified with a tag <ion-col>
.
<ion-row>
<ion-col width-50 class="job-item">Job A</ion-col>
<ion-col width-50 class="job-item">Job B</ion-col>
</ion-row>
I need to be able to cycle through jobs:
<ion-row>
<ion-col *ngFor="let job of jobs" width-50 class="job-item">{{ job.name }}</ion-col>
</ion-row>
But the problem is that all tasks are displayed in one tag <ion-row>
.
Instead, I need something like this pseudocode:
<ion-row>
<ion-col>1</ion-col>
<ion-col>2</ion-col>
</ion-row>
<ion-row>
<ion-col>3</ion-col>
<ion-col>4</ion-col>
</ion-row>
<ion-row>
<ion-col>5</ion-col>
<ion-col>6</ion-col>
</ion-row>
<ion-row>
<ion-col>7</ion-col>
</ion-row>
How can I achieve this? Presumably using odd / even numbers?
source to share
create a channel that does the splitting:
@Pipe({ name: "row" })
export class RowPipe implements PipeTransform {
// input is an array of any
// mod is the modulo, every mod items, create a row
transform(input: any[], mod: number): any[][] {
return input.reduce((previous, next, index) => {
if (index % mod === 0)
previous.push([next]);
else
previous[previous.length - 1].push(next);
return previous;
}, <any[][]>[]);
}
}
then:
<ion-row *ngFor="row of jobs|row:2">
<ion-col *ngFor="let job of row" width-50 class="job-item">{{ job.name }}</ion-col>
</ion-row>
source to share
The best way to do this is to convert your array structure jobs
to be an array of arrays. Then the structure you want is simple:
<ion-row *ngFor='let row of jobRows'>
<ion-col *ngFor="let job of row">{{ job.name }}</ion-col>
</ion-row>
Where you do the conversion mostly depends on your application, but you can do it in a pipe:
@Pipe({
name: 'toRows'
})
export class ToRowsPipe implements PipeTransform {
transform<T>(value: T[], perRow: number): T[][] {
let rows: T[][] = [];
for (let i = 0; i < value.length; i += perRow) {
rows.push(value.slice(i, i + perRow))
}
return rows;
}
}
<ion-row *ngFor='let row of jobs | toRows:2'>
<ion-col *ngFor="let job of row">{{ job.name }}</ion-col>
</ion-row>
source to share