DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Leonel Elimpe
Leonel Elimpe

Posted on • Originally published at leonelngande.com on

4 Angular NgForOf Exported Values I Was Not Aware Of - first, last, even, and odd

Angular's NgForOf provides exported values that can be aliased to local variables. Until today, I've only been aware of the index exported value, turns out there's a couple more.

Four of them in particular are very applicable in my day-to-day usage of Angular: first, last, even, and odd.

  • first

first, a boolean value, is true when the item is the first item in the iterable.

  • last

last, a boolean value, is true when the item is the last item in the iterable.

  • even

even, a boolean value, is true when the item has an even index in the iterable.

  • odd

odd, a boolean value, is true when the item has an odd index in the iterable.

Not leaving out index, a number representing the index of the current item in the iterable.

Here's a usage example in which we alias the above five exported values to local variables:

<li *ngFor="let user of users; index as i; first as isFirst; last as isLast; even as isEven; odd as isOdd">
  {{user}} <span *ngIf="isFirst">default</span>
</li>
Enter fullscreen mode Exit fullscreen mode

And that's it πŸ™‚, hope this is useful to you in some way.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!