seyid yagmur
seyid yagmur

Reputation: 1722

Angular's nativeElement's offsetWidth is 0

I've tried to get offset data of the component 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 component.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.

Upvotes: 2

Views: 5873

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73761

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:

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

See this stackblitz for a demo.

Upvotes: 5

Sam
Sam

Reputation: 46

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 comment.

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

Upvotes: 0

Related Questions