Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 762
tom10271 Avatar asked Feb 04 '16 06:02

tom10271


People also ask

What is ngFor last?

last: boolean : True when the item is the last item in the iterable. even: boolean : True when the item has an even index in the iterable. odd: boolean : True when the item has an odd index in the iterable.

How does* ngFor work?

NgFor is a structural directive, meaning that it changes the structure of the DOM . It's point is to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding.

Which directive is used to loop through and display elements of an array in the HTML file of Angular project?

To Use ngFor directive, you have to create a block of HTML elements, which can display a single item of the items collection. After that you can use the ngFor directive to tell angular to repeat that block of HTML elements for each item in the list.

Can we use for loop in Angular?

The for–in loop is for looping over object properties. The for–of loop is for looping over the values in an array. for–of is not just for arrays. It also works on most array-like objects including the new Set and Map types which we will cover in the next lecture.


3 Answers

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
like image 194
vusan Avatar answered Oct 19 '22 05:10

vusan


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

like image 33
Günter Zöchbauer Avatar answered Oct 19 '22 04:10

Günter Zöchbauer


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

like image 32
Joshua Szuslik Avatar answered Oct 19 '22 03:10

Joshua Szuslik