首页 文章

对于观察者来说,偏移和离开

提问于
浏览
2

我在* ngFor中有一个动态创建的组件,如何在ViewChildren中获取它们后获得offsettop和offsetleft .

模板

<anchor #myanchor></anchor>

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

这是ngAfterViewInit

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

我可以通过ViewChild获取单个元素的位置,但需要ViewChildren的帮助 . 任何指针将不胜感激 .

1 回答

  • 0
    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

相关问题