【问题标题】:offsettop and offsetleft for viewchildrenviewchildren 的 offsettop 和 offsetleft
【发布时间】:2017-06-11 13:41:14
【问题描述】:

我在 *ngFor 中有一个动态创建的组件,我如何在 ViewChildren 中获取这些组件的 offsettop 和 offsetleft。

模板

<anchor #myanchor></anchor>

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

这里是 ngAfterViewInit

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

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

【问题讨论】:

    标签: angular offset viewchild


    【解决方案1】:
    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

    【讨论】:

    • 谢谢甘特。元素上的 offsetTop 或 offsetHeight 显示父元素中的相对高度。有没有办法获取页面上的绝对坐标?
    • 不知道,不过和普通的JS一样。
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多