Reputation: 4217
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
Upvotes: 6
Views: 10262
Reputation: 1750
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
Upvotes: 4
Reputation: 55443
I'd prefer to use custom directive which will work for you.
Demo : https://plnkr.co/edit/XO1GjQTejR8MxoagTZR5?p=preview check broswer's console
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[getRef]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){ }
show(){
console.log(this.el.nativeElement);
console.log(this.el.nativeElement.offsetLeft);
}
}
Upvotes: 1