javascript - Angular's nativeElement's offsetWidth is 0 - Stack Overflow

I've tried to get offset data of the ponent in my angular app as below.this.el.nativeElement.offse

I've tried to get offset data of the ponent in my angular app as below.

this.el.nativeElement.offsetWidth

But it is returning 0 if I don't pass it's css property as below.

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

it is working as I want.returning real value of the native ponent.But I don't want to change the position property.

Do you suggest me any solution to get current offset data like offsetWidth etc.. you can work on here.

I've tried to get offset data of the ponent in my angular app as below.

this.el.nativeElement.offsetWidth

But it is returning 0 if I don't pass it's css property as below.

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

it is working as I want.returning real value of the native ponent.But I don't want to change the position property.

Do you suggest me any solution to get current offset data like offsetWidth etc.. you can work on here.

Share Improve this question edited Jun 19, 2019 at 13:03 Martin Parenteau 73.9k13 gold badges135 silver badges155 bronze badges asked Jun 19, 2019 at 12:11 seyid yagmurseyid yagmur 1,72218 silver badges27 bronze badges 3
  • Is the object visible on the page? If not, measurements will always return 0. Maybe setting position is making it visible – Ruan Mendes Commented Jun 19, 2019 at 12:14
  • yeah it is visible. @JuanMendes – seyid yagmur Commented Jun 19, 2019 at 12:15
  • you need to use @ViewChild, you can check example here: stackblitz./edit/… – mocni_T Commented Jun 19, 2019 at 12:31
Add a ment  | 

2 Answers 2

Reset to default 5

This happens because the ponent 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:

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

See this stackblitz for a demo.

Some times the element might not have reference to the DOM object. Try doing change detection to refresh the reference. Sorry I am not able to ment.

import ChangeDetectorRef in the constructor

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; 
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745146011a4613649.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信