This could be better handled in the controller. In case of default change detection strategy, the template is reloaded multiple times without our control or knowledge. So it’s better to make sure the tasks variable has atleast 5 elements in the controller rather than to control the flow in the template. You could something like the following in the controller and leave the template unchanged.
for (let i = 0; i < 5; i++) {
if(!this.tasks[i].id) {
this.tasks[i].id = '';
}
}
Problem :
I have a requirement to always display minimum of 5 rows(5 or more rows) in a table. For example, if there are 2 rows available in Database, I need to display other 3 more rows in UI with empty rows.
Here is what I tried so far:
<div *ngFor="let task of tasks; let i = index">
<div class="rowDiv">{{task.id}}</div>
</div>
Here I want to run the loop from i = tasks.size to i < = 5. So that I have total of 5 rows in UI. How to achieve this?
<div *ngFor=" let i = index">
<div class="rowDiv"></div>
</div>
Comments
Comment posted by Marcel Hoekstra
Like Alex mentions, the easiest way is to make sure the taks array exist of 5 element. Like this: let tasks= [‘task 1’, ‘task 2’, ‘task 3’]; tasks = tasks.length < 5 ? [...new Array(5)].map((_, i) => tasks.length >= i ? tasks[i] : null) : tasks;
Comment posted by Manish
Are you fetching the data from the API? If so, do you have control over the API? If so, you can easily do this in API. If not, this can be done in the typescript.
Comment posted by code_buddy
What do you mean API? I am fetching the values from the backend REST service that is exposed.
Comment posted by code_buddy
This is closer to what I wanted. However, in this way I get maximum 5 elements in the UI. My requirement is minimum 5 elements should be displayed in UI at any point. However, this list can grow from backend and the items will be scrolled in the table.