Angular 2 Get the width of the div

I looked through a lot of posts, but nobody does what I want. I have a table that goes beyond the page width and for various reasons I need to get its width.

I used:

@ViewChild('tableToMeasure') elementView: ElementRef;

And then put #tableToMeasure in the table. However, this seems like a mistake:

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

Even if it works and only on the parent div of the page.

Any ideas? I need to get its width both for loading the page, and for resizing the page, and change the other width of the divs to one value.

+4
source share
3 answers

elementViewwill not be installed before the call ngAfterViewInit. If you have code in ngOnInitor constructor, you will get this error.

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

    @ViewChild('tableToMeasure') elementView;

    constructor() {
    }

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

I had the same problem. The solution I found was pretty easy; it returns undefined because there is nothing defined as "tableToMeasure" in your HTML file.

Therefore, you need to add #tableToMeasureto your HTML element.

Sample HTML file code:

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

And in your TypeScript file:

@ViewChild('tableToMeasure')elementView: ElementRef;

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

Good luck

+1
source

Source: https://habr.com/ru/post/1676650/


All Articles