typescript Angular 2 获取div的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43845822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:31:43  来源:igfitidea点击:

Angular 2 Get width of a div

angulartypescript

提问by Andrew Junior Howard

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:

然后将#tableToMeasure 放在桌子上。然而,这似乎是错误的:

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.

即使这仅适用于页面的父 div。

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.

有任何想法吗?我需要在页面加载和页面调整大小时获取它的宽度,并将另一个 div 宽度更改为相同的值。

采纳答案by Günter Z?chbauer

elementViewwon't be set before ngAfterViewInitwas called. If you have your code in ngOnInitor the constructor, you'll get this error.

elementViewngAfterViewInit被调用之前不会被设置。如果你有你的代码ngOnInit或构造函数,你会得到这个错误。

回答by Dmitrij Kuba

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

    @ViewChild('tableToMeasure') elementView;

    constructor() {
    }

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

回答by Sverre Boer

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'.

我有同样的问题。我找到的解决方案实际上相当容易;它返回 undefined 因为在您的 HTML 文件中没有定义为“tableToMeasure”。

Therefore you have to add #tableToMeasureto your HTML element.

因此,您必须添加#tableToMeasure到您的 HTML 元素。

Example code HTML file:

示例代码 HTML 文件:

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

And in your TypeScript file:

在你的 TypeScript 文件中:

@ViewChild('tableToMeasure')elementView: ElementRef;

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

确保从@angular/core.

Good luck!

祝你好运!