Angular 2获取div的宽度 [英] Angular 2 Get width of a div

查看:395
本文介绍了Angular 2获取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.

我用过:

@ViewChild('tableToMeasure') elementView: ElementRef;

然后将#tableToMeasure放在桌子上.但这似乎是错误的:

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

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

即使此方法仅在页面的父div上起作用.

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

有什么想法吗?我需要在页面加载和页面调整大小时都获得它的宽度,然后将另一个divs宽度更改为相同的值.

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.

推荐答案

elementView不会在调用ngAfterViewInit之前设置. 如果您的代码位于ngOnInit或构造函数中,则会出现此错误.

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

这篇关于Angular 2获取div的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆