[英]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
样式属性更改为block
或inline-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.