Reputation: 12179
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
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
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}}
Upvotes: 0
Reputation: 245
Try to use:
const rect = this.element.nativeElement.getBoundingClientRect();
const width = rect.width;
Upvotes: 0