我在 *ngFor 中有一个动态创建的组件,在将它们放入 ViewChildren 中后如何获取这些组件的 offsettop 和 offsetleft。
模板
<anchor #myanchor></anchor>
类别
@ViewChildren('myanchor') anchors: QueryList<any>;
这是 ngAfterViewInit
ngAfterViewInit(){
this.anchors.map(i=>{ console.log(i); })
}
我可以通过 ViewChild 获取单个元素的位置,但需要 ViewChildren 的帮助。任何指示将不胜感激。
最佳答案
ngAfterViewInit(){
this.anchors.toArray()
.map(i=>{ console.log(i.nativeElement.offsetTop); })
}
如果 #myanchor
位于组件或指令上,而不是普通 DOM 元素上,则需要添加 read
来获取 ElementRef
@ViewChildren('myanchor', {read: ElementRef}) anchors: QueryList<ElementRef>;
另请参阅angular 2 / typescript : get hold of an element in the template
关于angular - viewchildren 的 offsettop 和 offsetleft,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867464/