el_pup_le
el_pup_le

Reputation: 12179

How to get width of absolute positioned element in Angular

I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().

constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}

Element style:

display: block;
position: absolute;
left: 100;

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?

Update:

I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

Upvotes: 2

Views: 834

Answers (3)

Bohdan Khodakivskyi
Bohdan Khodakivskyi

Reputation: 632

Try to move your code to AfterViewInit lifecycle hook method and use @ViewChild() decorator instead of injecting element directly in constructor.

Try this code:

import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <div #child>
      <h2>Hello!</h2>
    </div>
  `,
})
export class App implements AfterViewInit {
  @ViewChild('child') element: any;
  htmlElement: HTMLElement;

  constructor() {}

  ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    let width = this.element.nativeElement.offsetWidth;
  }
}

Or see the working example here. Also check comments for explanations.

Upvotes: 1

Aravind
Aravind

Reputation: 41571

You should associate it to the element to the elementRef

@ViewChild('foo') foo: TemplateRef;

<div #foo>
    <h2>Hello {{name}}</h2>
</div>
    {{foo.clientWidth}}

LIVE DEMO

Upvotes: 0

DmitriyKhirniy
DmitriyKhirniy

Reputation: 245

Try to use:

const rect = this.element.nativeElement.getBoundingClientRect();
const width = rect.width;

Upvotes: 0

Related Questions