Reputation: 2123
Data
const arr = [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];
I want to split that data to 3 columns and want to appers as follow:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
...
<li>10</li>
</ul>
<ul>
<li>11</li>
<li>12</li>
<li>13</li>
...
<li>20</li>
</ul>
<ul>
<li>21</li>
<li>22</li>
<li>23</li>
...
<li>30</li>
</ul>
How can I split data when using ngfor?
<ul *ngFor="let item of arr">
<li>{{item}}</li>
</ul>
Upvotes: 3
Views: 4202
Reputation: 106
name = 'Angular';
objectKeys = Object.keys;
arr = [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];
arr2 = { 0 : 10, 10 : 20, 20 : 30};
<ul *ngFor="let key of objectKeys(arr2)">
<ng-container *ngFor="let item of arr" >
<li *ngIf="item > key && item <= arr2[key]" >{{item}}</li>
</ng-container>
</ul>
Upvotes: 1
Reputation: 5272
function chunkArray(myArray, chunk_size){
var results = [];
while (myArray.length) {
results.push(myArray.splice(0, chunk_size));
}
return results;
}
var arr = [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];
// Split in group of 3 items
arr = chunkArray(arr, 3);
add nested *ngFor in the HTML
<ul *ngFor="let chunckedArr of arr">
<li *ngFor="let item of chunckedArr">{{item}}</li>
</ul>
Upvotes: 2
Reputation: 1481
You can use slice :
<ul>
<li *ngFor="let item of arr.slice(0,10)">{{item}}</li>
</ul>
<ul>
<li *ngFor="let item of arr.slice(10,20)">{{item}}</li>
</ul>
<ul>
<li *ngFor="let item of arr.slice(20,30)>{{item}}</li>
</ul>
Upvotes: 3
Reputation: 5121
First of all, it should be like this :
<ul>
<li *ngFor="let item of arr">{{item}}</li>
</ul>
And add this in your CSS :
ul{
-webkit-columns: 3;
-moz-columns: 3;
columns: 3;
}
Upvotes: 13