【问题标题】:Angular's nativeElement's offsetWidth is 0角度 nativeElement offsetWidth 为 0
【发布时间】:2019-11-02 04:11:18
【问题描述】:

我尝试在我的 Angular 应用程序中获取组件的偏移数据,如下所示。

this.el.nativeElement.offsetWidth

但如果我不通过它的 css 属性,它会返回 0,如下所示。

this.renderer.setStyle(this.el.nativeElement, 'position', 'fixed');

它按我的意愿工作。返回本机组件的实际价值。但是 我不想更改 position 属性。

您是否建议我使用任何解决方案来获取当前偏移数据,例如 offsetWidth 等。 你可以在here上工作。

【问题讨论】:

  • 对象在页面上是否可见?如果没有,测量值将始终返回 0。也许设置位置使其可见
  • 是的,它是可见的。 @JuanMendes
  • 你需要使用@ViewChild,你可以在这里查看示例:stackblitz.com/edit/…

标签: javascript angular dom angular7


【解决方案1】:

有时元素可能没有对 DOM 对象的引用。尝试进行更改检测以刷新参考。抱歉,我无法发表评论。

在构造函数中导入 ChangeDetectorRef

constructor(private changeDetect: ChangeDetectorRef) {}

@ViewChild('splashScreen') el: ElementRef;

getOffSetWidth() {
    // run change detection
    this.changeDetect.detectChanges();
    // And then try getting the offset
    const offsetWidth = this.el.nativeElement.offsetWidth;
    return offsetWidth; 
}

【讨论】:

    【解决方案2】:

    这是因为组件默认是内联元素。您可以将其display 样式属性更改为blockinline-block 以在代码中获得正确的大小:

    :host {
      display: block; /* or display: inline-block; */
    }
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-19
      • 2017-12-17
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2011-08-23
      相关资源
      最近更新 更多