Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the length of an Observable array

In my Angular 2 component I have an Observable array

list$: Observable<any[]>;

In my Template I have

<div *ngIf="list$.length==0">No records found.</div>

<div *ngIf="list$.length>0">
    <ul>
        <li *ngFor="let item of list$ | async">item.name</li>
    </ul>
</div>

But list$.length doesn't work with in case of Observable array.

Update:

It seems that (list$ | async)?.length gives us the length but the below code still doesn't work:

<div>
    Length: {{(list$ | async)?.length}}
    <div *ngIf="(list$ | async)?.length>0">
        <ul>
            <li *ngFor="let item of (list$ | async)">
                {{item.firstName}}
            </li>
        </ul>
    </div>
</div>

Can anyone please guide how do I check length of Observable array.

like image 583
Naveed Ahmed Avatar asked Jun 27 '16 15:06

Naveed Ahmed


3 Answers

You can use the | async pipe:

<div *ngIf="(list$ | async)?.length==0">No records found.</div>

Update - 2021-2-17

<ul *ngIf="(list$| async) as list; else loading">
   <li *ngFor="let listItem of list">
      {{ listItem.text }}
   </li>
</ul>

<ng-template #loading>
  <p>Shows when no data, waiting for Api</p>
  <loading-component></loading-component>
</ng-template>

Update - Angular Version 6:

If you are loading up a css Skeleton you can use this. If the array has no items it will display the css template. If there is data then fill out the ngFor.

<ul *ngIf="(list$| async)?.length > 0; else loading">
   <li *ngFor="let listItem of list$| async">
      {{ listItem.text }}
   </li>
</ul>

<ng-template #loading>
  <p>Shows when no data, waiting for Api</p>
  <loading-component></loading-component>
</ng-template>
like image 96
Günter Zöchbauer Avatar answered Nov 07 '22 00:11

Günter Zöchbauer


A solution for .ts-Files:

     this.list.subscribe(result => {console.log(result.length)});
like image 40
Blank Avatar answered Nov 07 '22 00:11

Blank


For Angular 4+, try this

<div *ngIf="list$ | async;let list">
    Length: {{list.length}}
    <div *ngIf="list.length>0">
        <ul>
            <li *ngFor="let item of list">
                {{item.firstName}}
            </li>
        </ul>
    </div>
</div>
like image 23
MD KAMRUL HASAN SHAHED Avatar answered Nov 07 '22 00:11

MD KAMRUL HASAN SHAHED