How to get the last element of an array in Angular2 template WITHOUT LOOPING EVERYTHING?

16,803

Solution 1

You can't assign arbitrary values to template variables. Template variables are for references to elements and directives and locals used for structural directives.

Solution 2

You can use boolean keyword last, here in this example:

<div *ngFor="let item of items;let last = last;let first = first;let index = index">
first:{{first}}
index:{{index}}
last:{{last}}
</div>

result:

first:true index:0 last:false
first:false index:1 last:false
first:false index:2 last:false
first:false index:3 last:true

Solution 3

You would set the lastelement variable in your template loop. Angular will automatically bind the last element in your loop to the last directive.

<div *ngFor="#item of items; #lastElement = last">
   // Items go here
</div>

https://angular.io/docs/ts/latest/api/common/NgFor-directive.html

Share:
16,803
tom10271
Author by

tom10271

Web Developer &amp; JS guru Angular, Angular2, Typescript, Symfony

Updated on June 24, 2022

Comments

  • tom10271
    tom10271 almost 2 years

    This question is not asking how to get access to looping variables like i, first, last but how to retrieve and set variable as TEMPLATE VARIABLES.


    This is not working...

    <div #lastElement="arr[arr.length-1]"></div>
    

    So I actually need to create a local variable in component then bind it directly?

    I feel lots of stuff I can do it with ng-* directives in the past are all required to hardcode in Component... Kind of degrading tbh

  • Joshua Szuslik
    Joshua Szuslik almost 6 years
    The question is to do it without looping everything. My answer below should be the correct answer.
  • tom10271
    tom10271 over 5 years
    @JoshuaSzuslik You are looping too