Andrew Howard
Andrew Howard

Reputation: 3092

Angular 2 Get width of a div

I've looked at numerous posts but none quite do what I want it to do. I have a table which goes outside the width of the page and for various reasons I need to get it's width.

I used:

@ViewChild('tableToMeasure') elementView: ElementRef;

And then put #tableToMeasure on the table. However this seems to error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

Even though this works on and only on the parent div of the page.

Any ideas? I need to get it's width on both page load and page resize and change another divs width to be the same value.

Upvotes: 9

Views: 20444

Answers (3)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658263

elementView won't be set before ngAfterViewInit was called. If you have your code in ngOnInit or the constructor, you'll get this error.

Upvotes: 4

Sverre Boer
Sverre Boer

Reputation: 41

I had the same problem. The solution I found was actually fairly easily; it returns undefined because in your HTML file there is nothing defined as 'tableToMeasure'.

Therefore you have to add #tableToMeasure to your HTML element.

Example code HTML file:

<div #tableToMeasure style="width: 100px; height: 100px">
   <span>Some content!</span
</div>

And in your TypeScript file:

@ViewChild('tableToMeasure')elementView: ElementRef;

Make sure to import ViewChild and ElementRef from @angular/core.

Good luck!

Upvotes: 4

Dmitrij Kuba
Dmitrij Kuba

Reputation: 1038

@Component({
    selector: 'selector',
    template: `<button #tableToMeasure>Click me</button>`
})
export class FeatureComponent implements AfterViewInit {

    @ViewChild('tableToMeasure') elementView;

    constructor() {
    }

    ngAfterViewInit() {
        console.log(this.elementView.nativeElement);
    }
}

Upvotes: 5

Related Questions