简体   繁体   English

Angular 的 nativeElement 的 offsetWidth 为 0

[英]Angular's nativeElement's offsetWidth is 0

I've tried to get offset data of the component in my angular app as below.我试图在我的 angular 应用程序中获取组件的偏移数据,如下所示。

this.el.nativeElement.offsetWidth

But it is returning 0 if I don't pass it's css property as below.但是如果我不传递它的 css 属性,它将返回0 ,如下所示。

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

it is working as I want.returning real value of the native component.But I don't want to change the position property.它按我的意愿工作。返回本机组件的实际值。但我不想更改position属性。

Do you suggest me any solution to get current offset data like offsetWidth etc.. you can work on here .您是否建议我获取当前偏移数据(如 offsetWidth 等)的任何解决方案。您可以在这里工作。

This happens because the component is an inline element by default.发生这种情况是因为组件默认是内联元素。 You can change its display style attribute to block or inline-block to get the correct size in code:您可以将其display样式属性更改为blockinline-block以获得正确的代码大小:

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

See this stackblitz for a demo.有关演示,请参阅此 stackblitz

Some times the element might not have reference to the DOM object.有时元素可能没有对 DOM 对象的引用。 Try doing change detection to refresh the reference.尝试进行更改检测以刷新参考。 Sorry I am not able to comment.抱歉,我无法发表评论。

import ChangeDetectorRef in the constructor在构造函数中导入 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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript的offsetWidth对Safari不起作用 - Javascript's offsetWidth not working for Safari Angular2测试:ComponentFixture中DebugElement和NativeElement对象之间的区别是什么? - Angular2 testing: What's the difference between a DebugElement and a NativeElement object in a ComponentFixture? 计算span的scrollWidth,offsetWidth,clientWidth的值 - Calculate the value of span's scrollWidth,offsetWidth,clientWidth 我可以轻松地“设置”元素的offsetWidth吗? - Can I easily “set” an element's offsetWidth? 制作桌子的 <tbody> 使用display:block和offsetWidth可滚动 - Making table's <tbody> scrollable using display:block and offsetWidth 当元素快速调整大小时,JavaScript的offsetWidth和offsetHeight给出错误的值 - JavaScript's offsetWidth and offsetHeight give wrong value when element is resizing quickly 无法捕获自定义角度组件的nativeElement - Unable to capture nativeElement for custom angular components Angular2 ElementRef nativeElement检查元素是否被禁用 - Angular2 ElementRef nativeElement check if element is disabled 类型错误:无法读取未定义 Angular 8 的属性“nativeElement” - TypeError: Cannot read property 'nativeElement' of undefined Angular 8 Angular nativeElement.scrollTop 有奇怪的行为 - Angular nativeElement.scrollTop has weird behavior
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM