Javascript 页面加载后如何在Angular 4中获取(DOM)元素的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48708119/
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
How to get width of (DOM) Element in Angular 4 after page is loaded
提问by mpro
I'm looking for a solution in Angular 4 to get the width of DOM element without taking any action (click or window resize), just after the page is loaded, but before I start to draw the svg. I've found a similar case in herebut it doesn't work for me. I get the same error:
我正在 Angular 4 中寻找一个解决方案来获取 DOM 元素的宽度,而无需采取任何操作(单击或调整窗口大小),就在页面加载之后,但在我开始绘制 svg 之前。我在这里找到了一个类似的案例,但它对我不起作用。我犯了同样的错误:
ERROR TypeError: Cannot read property 'nativeElement' of undefined
错误类型错误:无法读取未定义的属性“nativeElement”
I need to get the width of div container to set veiwbox of svg I'm drawing inside it.
我需要获取 div 容器的宽度来设置我在其中绘制的 svg 的 veiwbox。
Here is the template:
这是模板:
<div id="what-is-the-width" class="svg-chart-container">
<svg [innerHTML]="svg"></svg>
</div>
and TS file with stuff needed in this case:
和 TS 文件,在这种情况下需要的东西:
import { Component, Input, OnInit, ViewEncapsulation, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
export class SvgChartComponent implements OnInit {
@ViewChild('what-is-the-width') elementView: ElementRef;
constructor() { }
ngAfterViewInit() {
console.log(this.elementView.nativeElement);
}
ngOnInit() {
//this method gets the data from the server and draw the svg
this.getSVGChartData();
}
}
Does anyone have ideas how to get this working?
有没有人有想法如何让这个工作?
回答by
You can't have the size of an element before the page is loaded. In case it's not clear enough, if the page isn't loaded, then your HTML element isn't loaded.
在页面加载之前,您不能拥有元素的大小。如果不够清楚,如果页面未加载,则您的 HTML 元素未加载。
If you want to set the viewbox of your SVG according to a div, you will need to wait for the page to load, then change the viewbox. It's perfectly doable.
如果要根据 div 设置 SVG 的视图框,则需要等待页面加载,然后更改视图框。这是完全可行的。
The fastest way of doing that is :
最快的方法是:
<div #container>Container's width is {{ container.offsetWidth }}</div>
<svg:svg [width]="container.offsetWidth"></svg>
I'll let you deal with the viewBox attribute, since I don't really know what you want to do with it.
我会让你处理 viewBox 属性,因为我真的不知道你想用它做什么。
You need to add the svg:prefix to tell angular it's not a custom directive, by the way.
svg:顺便说一下,您需要添加前缀来告诉 angular 它不是自定义指令。

