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
2 Answers
Reset to default 5This 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;
}