9

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.

3 Answers 3

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

    @ViewChild('tableToMeasure') elementView;

    constructor() {
    }

    ngAfterViewInit() {
        console.log(this.elementView.nativeElement);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm sorry I tried that but still getting the same error.
4

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

7 Comments

So I have to use it within ngAfterViewInit()?
So he should use elementView only after the viw initialized? So, inside ngAfterViewInit?
Either inside ngAfterViewInit or anything that's executed later, for example an event handler for user actions (click, scroll, ...)
Hmm I tried it on ngAfterViewInit() but still getting same error
Hard to tell from the single line of code you posted. Please provide more information than I can have another look. Ideally a Plunker that allows to reproduce. (Plunker provides an Angular template to get you started easily)
|
4

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.