Reputation: 816
Say I got an array from the server.
var arr = [
{ ID: "001", Name: "a00", isChecked: "true" },
{ ID: "002", Name: "b00", isChecked: "true" },
{ ID: "003", Name: "c00", isChecked: "true" },
{ ID: "004", Name: "d00", isChecked: "true" },
{ ID: "005", Name: "e00", isChecked: "true" },
{ ID: "006", Name: "f00", isChecked: "true" },
{ ID: "007", Name: "g00", isChecked: "true" },
{ ID: "008", Name: "h00", isChecked: "true" },
{ ID: "009", Name: "i00", isChecked: "true" },
{ ID: "010", Name: "j00", isChecked: "true" },
{ ID: "011", Name: "k00", isChecked: "true" },
{ ID: "012", Name: "l00", isChecked: "true" },
{ ID: "013", Name: "m00", isChecked: "true" },
{ ID: "014", Name: "n00", isChecked: "true" },
{ ID: "015", Name: "o00", isChecked: "true" },
{ ID: "016", Name: "p00", isChecked: "true" },
// ....many many rows
]
Now I want to display it in a table with a certain number of columns. For example, if I want to display it in 4 columns. Then I use
<tbody>
<tr *ngFor="let group of arr">
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
</tr>
The expected result likes
a00 | b00 | c00 | d00
e00 | f00 | g00 | h00
.....
If I chose 7 columns. Then the code is:
<tbody>
<tr *ngFor="let group of arr">
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
<td>{{group.name}}</td>
</tr>
The expected result likes:
a00 | b00 | c00 | d00 | e00 | f00 | g00
....
However I don't know if it is 4 or 7, the chunk size is given by a variable size
. So how to do it?
Upvotes: 1
Views: 755
Reputation: 15423
You may do so using:
.ts
newArr = []
size = 2; // change this as per your requirement
ngOnInit() {
while (this.arr.length) {
this.newArr.push(this.arr.splice(0, this.size)); // create 2D array
}
}
.html
<table>
<tbody>
<tr *ngFor="let outer of newArr">
<td *ngFor="let group of outer">{{group.Name}}</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 533
Based on the size
variable you can create an array with the length of size and use another *ngFor
with that array to render the columns.
Example
class MyComponent extend OnInit {
size = 4;
sizeArray = [];
ngOnInit() {
this.sizeArray = new Array(this.size)
}
}
<tbody>
<tr *ngFor="let group of arr">
<td *ngFor="let index of sizeArray">
{{group.name}}
</td>
</tr>
</tbody>
Upvotes: 0