Reputation: 865
I want to loop my table for a constant 10 rows. If my array has only 5 items , it has to have the remaining 5 rows with empty value.
This is how I output my table:
<tr *ngFor="let item of items">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.desc}}</td>
</tr>
How do I make sure it always has 10 rows? Please help, thank you!
Upvotes: 0
Views: 20960
Reputation: 131
Try this .
<tr *ngFor="let index of [0,1,2,3,4,5,6,7,8,9]">
<td>{{items[index]?.id}}</td>
<td>{{items[index]?.name}}</td>
<td>{{items[index]?.desc}}</td>
</tr>
You can use Array.fill for instead of [0,1,2,3,...].
Upvotes: 0
Reputation: 1672
This is one of those things where it's perhaps worth not overthinking it - if you want to enforce a number of rows, and it's a low number such as 10, then you can just code the table explicitly like that:
<tr>
<td>{{items[0].id}}</td>
<td>{{items[0].name}}</td>
<td>{{items[0].desc}}</td>
</tr>
<tr>
<td>{{items[1].id}}</td>
<td>{{items[1].name}}</td>
<td>{{items[1].desc}}</td>
</tr>
...
Angular should handle the empty values gracefully.
A better solution however, perhaps if you want to change the number dynamically etc, is you can simply fill your array with null values in your model.
You can use Array.fill for this.
Like so:
if(array.length < 10){
array = array.fill(null,array.length, 10);
}
Likewise you can easily truncate an array for results that are over 10.
Upvotes: 1
Reputation: 69
you need to first check the array size in typescript file for example
array:any=[];
DataAssign(){
array=//your data;
now check the array size
if(array.length<=5){
now make object fo array and push ex
for(int i=0; i<=(array.length-10); i++)
{
let obj={id:"",name:"",desc:""};
array.push(obj);
}
}
}
Upvotes: 1