How to catch the length of a *ngFor?

Asked

Viewed 458 times

0

I own a property elemento$ inside my component, whose type is Observable<Objeto[]>. I used the directive *ngFor to access the data individually and show them on the screen:

<ul>
  <li *ngFor="let elemento of elemento$ | async">
    <p>{{elemento.mensagem}}</p>
  </li>
</ul>

When performing the activity, I had to insert a tag that should not appear when I access the first element of the array, which I solved so:

<ul>
  <li *ngFor="let elemento of elemento$ | async; let i = index">
    <div *ngIf="!!i">isto não deve aparecer no primeiro elemento</div>
    <p>{{elemento.mensagem}}</p>
  </li>
</ul>

At the end of this, I also had to create a field that cannot be visible to the last element of the loop:

<ul>
  <li *ngFor="let elemento of elemento$ | async; let i = index">
    <div *ngIf="!!i">isto não deve aparecer no primeiro elemento</div>
    <p>{{elemento.mensagem}}</p>
    <div>isto não deve aparecer no último elemento</div>
  </li>
</ul>

To solve this, I used the following code:

<div *ngIf="i != ((elemento$ | async).length - 1)">isto não deve aparecer no último elemento</div>

But I don’t think it’s the ideal way to do it. There’s a way to do it using the properties of the directive itself *ngFor (ex: *ngfor="let x of y; let total = length")?

  • 1

    Confused this huh man!!

  • Gambi design Patterns

1 answer

2


The ngFor directive has the local variables below:

  • index: number; // returns the index of the current item in the array.
  • first: Boolean; // returns true if the item is first in the array.
  • last: Boolean; // returns true if the item is the last one in the array.
  • Even: Boolean; // returns true if the index is an even number in the array.
  • Odd: Boolean; // returns true if the index is an odd number in the array.
<ul *ngIf="elementos$ | async; let elementos" >
  <li *ngFor="let item of elementos; let first = first; let last = last">
    <div *ngIf="!first">isto não deve aparecer no primeiro elemento</div>
    <p>{{item.mensagem}}</p>
    <div *ngIf="!last">isto não deve aparecer no último elemento</div>
  </li>
</ul>

Reference

https://angular.io/api/common/NgForOf

https://blog.angular-university.io/angular-2-ngfor/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.