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
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.
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.
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.
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.
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
You can't assign arbitrary values to template variables. Template variables are for references to elements and directives and locals used for structural directives.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With