Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get length of items ngFor async / Observable<Aviso[]>;

Tags:

angular

ngfor

How can I get the total number of items using ngFor?

*ngFor="let aviso of avisosTest | async; let i = index"

I'm working with Firestore from Firebase with an Observable:

avisosTest: Observable<Aviso[]>;

I tried this but it did not work

{{ avisosTest.length }}

{{ avisosTest?.length }}
like image 270
Paco Zevallos Avatar asked Oct 17 '22 18:10

Paco Zevallos


2 Answers

in Angular 4 you can do this:

*ngFor="let aviso of avisosTest | async as aviso; let i = index"

And then you can call {{ avisosTest.length }} inside that tag.

Example

<ul>
  <li *ngFor="let aviso of avisosTest | async as aviso; let i = index">
    {{aviso}} - {{i + 1}} of {{aviso.length}}
  </li>
</ul>

Working Demo - wait 2 seconds for data load

If you need it outside of the loop, you can separate async and ngFor, like:

<div *ngIf="avisosTest | async as aviso">
  <ul>
    <li *ngFor="let aviso of aviso; let i = index">
      {{aviso}}
    </li>
  </ul>
  <div>
    {{aviso.length}} items total
  </div>
</div>

Working Demo - wait 2 seconds for data load

like image 92
Meligy Avatar answered Oct 21 '22 01:10

Meligy


I think you need

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

or

<div *ngIf="(avisosTest | async)?.length>0">{{avisosTest.legnth}}</div>
like image 31
Sajeetharan Avatar answered Oct 21 '22 02:10

Sajeetharan