I have the following code:
<ng-container *ngFor="let art of artefacts; let i = index">
<div *ngIf="art.isSelected == true" fxLayout="row" class="selected-artefacts">
</div>
</ng-container>
I find all items in artefacts and display if they have a property isSelected == true
. Now if there is no element in artefacts that has isSelected = true, I need to display "No items to display". How do I achieve this?
An alternative way to avoid IF/ELSE for this scenario uses CSS only, and it works in any framework (Angular, React, Vue, ...)
.no-item:not(:first-child) {
display:none;
}
Simply wrap the list with any tag (section, div, ul, ...) and add a last item with the message you want to display and add the class above.
Find a working example here: https://codepen.io/cacothi/pen/vYEJxKR
If you use a pipe to filter (| filter
) you can use
<div *ngFor="let item of artefacts">{{item.name}}
<input type="checkbox" [(ngModel)]="item.isSelected" (ngModelChange)="tick = tick+1">
</div>
<hr>
<ng-container *ngIf="artefacts | isSelected:tick as result; else noItems">
<!-- else is to cover the case where "artefacts" is "null" or "undefined" -->
<div *ngFor="let item of result; let i = index" fxLayout="row"
class="selected-artefacts">{{item.name}}</div>
<!-- the case where the pipe returns an empty array -->
<ng-container *ngIf="!result.length" [ngTemplateOutlet]="noItems"></ng-container>
</ng-container>
<ng-template #noItems>no Items</ng-template>
StackBlitz example
as
was added in https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc4-2017-03-17
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With