I have a component that uses NgFor
to build a row of elements...
<div *ngFor="let item of list">{{item.text}}</div>
I don't know how wide these elements are but later on I need to be able to reference a specific one, get its left
value and shift the whole lot so that the chosen one lines up with a certain point.
I've done this by adding id
to each element...
<div *ngFor="let item of list" [id]="item.id">{{item.text}}</div>
Then I just use the standard getElementById()
...
let el:HTMLElement = document.getElementById(someId);
let pos:number = el.offsetLeft;
This works fine but seems like the kind of thing that could probably be done in a more 'Angular2 way'. So my question is...
Is this approach ok? If not then what is the best way to get a reference to elements created by NgFor so that I can get their various positional and stylistic properties.
Cheers
In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.
Now, we will use *ngFor to display these names in the interface. In this example, we are creating an item using the let keyword of the friendlist array. It will iterate over each item in the array, and will print out the item name and item age, or any other object key we have in the array object.
Do it in code and assign it to each item and then just use it inside *ngFor . Such function calls from template bindings are discouraged.
In Angular2 for getting a reference to a specific index, you need to add let i = index inside the ngFor. Now you will get the index number in local variable,
NgFor provides several exported values that can be aliased to local variables:
In your case the div will look like this
<div *ngFor="let item of list ; let i = index">{{item.text}}</div>
Hope this will help you.
NgFor supports trackBy option. trackBy takes a function which has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.
For more details go through https://angular.io/docs/ts/latest/api/common/index/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