Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if my *ngFor returns empty?

Tags:

angular

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?

like image 266
Niranjan Shankar Avatar asked Jul 11 '17 12:07

Niranjan Shankar


2 Answers

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

like image 184
Caco Avatar answered Oct 05 '22 11:10

Caco


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

like image 22
Günter Zöchbauer Avatar answered Oct 05 '22 12:10

Günter Zöchbauer