popClingwrap
popClingwrap

Reputation: 4217

How to get reference to - and position of - an element created by NgFor

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

Answers (2)

Aswin KV
Aswin KV

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:

  • index will be set to the current loop iteration for each template context.
  • first will be set to a Boolean value indicating whether the item is the first one in the iteration.
  • last will be set to a Boolean value indicating whether the item is the last one in the iteration.
  • even will be set to a Boolean value indicating whether this item has an even index.
  • odd will be set to a Boolean value indicating whether this item has an odd index.

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

micronyks
micronyks

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

Related Questions