I have an array from 1 until 35:
numbersArray = [1,2,3,4,....,35]
I want to create a html table like the following:
---------------------------
1 |2 |3 |4 |5 |6 |7
---------------------------
8 |9 |10 |11 |12 |13 |14
---------------------------
15 |16 |17 |18 |19 |20 |21
---------------------------
22 |23 |24 |25 |26 |27 |28
---------------------------
29 |30 |31 |32 |33 |34 |35
---------------------------
I used the following:
<tr *ngFor="let number of numbersArray;">
<td>{{number}}</td>
</tr>
How can I add </td></tr><tr><td>
tags after 6 items in *ngFor
?
If it has to be a table and grouped into row you should make the data represent it like so.
Here's a Plunker
data
let cells = [];
for(var i =1; i <= 40 ; i++){
cells.push(i);
if((i % 7) == 0) {
this.rows.push(cells);
cells = [];
}
}
table
<table>
<tr *ngFor="let cells of rows;">
<td *ngFor="let c of cells;">{{c}}</td>
</tr>
</table>
You can either prepare data for that or create custom pipe like:
@Pipe({ name: 'chunks' })
export class ChunksPipe implements PipeTransform {
transform(arr: any, chunkSize: number) {
return arr.reduce((prev, cur, i) => (i % chunkSize) ? prev : prev.concat([arr.slice(i, i + chunkSize)]), []);
}
}
and then use it the following way:
<tr *ngFor="let chunk of numbersArray | chunks: 7">
<td *ngFor="let number of chunk">{{number}}</td>
</tr>
Plunker Example
Reduce your array into rows of item:
numbersArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
rowsArray = [];
...
this.rowsArray =
this.numbersArray.reduce((memo, item) => {
let itemsPerRow = 7;
if (!memo.length) { return memo = [...memo, [item]]; }
let lastItem = memo[memo.length-1];
if (lastItem.length < itemsPerRow) {
memo[memo.length-1] = [...lastItem, item];
} else {
memo = [...memo, [item]];
}
return memo;
}, []);
html:
<table>
<tr *ngFor="let row of rowsArray">
<td *ngFor="let item of row">
{{ item }}
</td>
</tr>
</table>
I found the solution without customize Pipe
or changing in numbersArray
<table>
<tr *ngFor="let row of [1, 2, 3, 4, 5]">
<td *ngFor="let col of [1, 2, 3, 4, 5, 6, 7]">
<div>{{numbersArray[(row -1) * 7 + col - 1]}}</div>
</td>
</tr>
</table>
https://plnkr.co/edit/VUw3j27EGVzZv8NZykWr?p=preview