如何在Angular中获取绝对定位元素的宽度

el_pup_le

我试图获取组件的宽度,但它为0。我还尝试将代码放入ngOnChanges()。

constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}

元素样式:

display: block;
position: absolute;
left: 100;

我尝试使用clientWidth(),但它也为0。如何获得角度2中的元素的宽度?

更新:

我不使用位置绝对值且宽度正确,所以我想问的问题是如何获取绝对位置元素的宽度?

Bohdan khodakivskyi

尝试将代码移至AfterViewInit生命周期挂钩方法,并使用@ViewChild()装饰器,而不是直接在中注入元素constructor

试试这个代码:

import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <div #child>
      <h2>Hello!</h2>
    </div>
  `,
})
export class App implements AfterViewInit {
  @ViewChild('child') element: any;
  htmlElement: HTMLElement;

  constructor() {}

  ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    let width = this.element.nativeElement.offsetWidth;
  }
}

或者在这里查看工作示例另请查看注释以获取解释。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章