2

I have a dynamically created component inside an *ngFor and how do I get the offsettop and offsetleft for those after getting them in a ViewChildren.

Template

<anchor #myanchor></anchor>

Class

@ViewChildren('myanchor') anchors: QueryList<any>;

Here is the ngAfterViewInit

ngAfterViewInit(){
    this.anchors.map(i=>{ console.log(i); })
}

I am able to get the position for a single element through ViewChild but need help with ViewChildren. Any pointers will be appreciated.

sv16
  • 125
  • 3
  • 7

1 Answers1

3
ngAfterViewInit(){
    this.anchors.toArray()
    .map(i=>{ console.log(i.nativeElement.offsetTop); })
}

If #myanchor is on a component or directive instead of a plain DOM element, you need to add read to get the ElementRef

@ViewChildren('myanchor', {read: ElementRef}) anchors: QueryList<ElementRef>;

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567