I am new in angular and I am using ngFor inside a to populate a table. My question is, if the array that is present[let i of user.acessTypes] in ngFor is empty how can I show an "Is Empty" string information in the correspondent row?
This is my table html
<table class="table table-bordered">
<tr>
<th>Email</th>
<th>Acess Type</th>
</tr>
<tr *ngFor="let user of listUser">
<td>{{user.email}}</td>
<td>
<button class="btn btn-primary"
*ngFor="let i of user.acessTypes">
//if i is empty show "Is Empty"
{{i.accessTypeName}}({{i.subAcessTypeName}})
</button> </td>
</tr>
</table>
This is my JSON response
{
"data": [
{
"id": 1,
"email": "jose@hotmail.com",
"password": "$2a$10$44ghfG4Ym4COxXbj9pDBuOLBXCPRRDiIM7y77G.XEh7avm2GOxlUC",
"isAdmin": 0,
"acessTypes": [
{
"id": 1,
"accessTypeName": "User",
"subAcessTypeName": "Ver&Escrever"
}
],
"tomas": [],
"consultas": [],
"profile": "NORMALUSER"
}
],
"dataArray": null,
"errors": []
}
There are several approaches. One of them is working with an if-else statement the Angular way. Both ng-container
and ng-template
won't be part of the DOM tree after they are rendered.
Here is a nice resource that explains it in more detail: https://toddmotto.com/angular-ngif-else-then
<table class="table table-bordered">
<tr>
<th>Email</th>
<th>Acess Type</th>
</tr>
<tr *ngFor="let user of listUser">
<td>{{user.email}}</td>
<td>
<ng-container *ngIf="user.acessTypes.length > 0; else noAccessTypes">
<button class="btn btn-primary" *ngFor="let i of user.acessTypes">
{{i.accessTypeName}}({{i.subAcessTypeName}})
</button>
</ng-container>
<ng-template #noAccessTypes>
<button class="btn btn-primary">Is empty</button>
</ng-template>
</td>
</tr>
</table>