8

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

4
  • That should work, what is the error you are receiving? Commented Feb 4, 2016 at 6:05
  • My suspicion is you are getting an undefined error due to the component binding before the data is ready. You might need to use a ternary to get around this. #lastElement="!!arr && arr.length > 0 ? arr[arr.length-1] : undefined" Commented Feb 4, 2016 at 6:08
  • Can you please elaborate a bit more on why you need this. Maybe there is another solution. Commented Feb 4, 2016 at 9:17
  • There is a list of social media icons, but only the last one requires a few more directives. Commented Feb 5, 2016 at 1:40

3 Answers 3

16

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
Sign up to request clarification or add additional context in comments.

2 Comments

The question is to do it without looping everything. My answer below should be the correct answer.
@JoshuaSzuslik You are looping too
3

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.