When dealing with an unknown number of items, one approach is to divide your array or list into smaller chunks containing 10 items each in your component class. This allows you to iterate through them effectively.
For instance, you can create a function like this in your component class:
chunkArray() {
let minutes = this.state.minutes.specificMinutes.selectedMinutes;
let chunks = [];
let chunkSize = 10;
for (let i = 0, j = minutes.length; i < j; i += chunkSize) {
chunks.push(minutes.slice(i, i + chunkSize));
}
return chunks;
};
Subsequently, in your template, utilize nested *ngFor
loops as demonstrated below:
<div *ngFor="let minutes of getChunks()" class="row">
<div *ngFor="let minute of minutes | keyvalue" class="col checkbox-container">
<div class="custom-control custom-checkbox">
<input type="checkbox" (click)="state.minutes.subTab='specificMinutes'" class="custom-control-input"
id="minute-{{minute.key}}-checkbox"">
<label class=" custom-control-label" for="minute-{{minute.key}}-checkbox">{{minute.key}}</label>
</div>
</div>
</div>
The first loop will render a row for each chunk, while the inner loop will display the individual elements within each chunk.
If needed, adjusting the value of chunkSize
will change the number of items per row dynamically.
Update
In scenarios where the total item count is not fixed and might not be evenly divisible by 10, the last chunk could have fewer than 10 items. To handle this situation, consider modifying your markup as follows:
<div *ngFor="let minutes of getChunks()" class="row">
<div class="offset-sm-1></div>
<div *ngFor="let minute of minutes | keyvalue" class="col-sm-1 checkbox-container">
...
</div>
<div class="offset-sm-1></div>
</div>
Alternatively, adjust the final array in the getChunks()
method to pad it with placeholder elements until there are 10 items. This way, your template will continue to display items uniformly.