我正在寻找Angular 4的解决方案,在不执行任何操作(单击或窗口调整大小)的情况下,获取DOM元素的宽度,仅在页面加载后但在开始绘制SVG之前。 我在这里找到了一个类似的案例,但对我没用。 我得到了同样的错误:
ERROR TypeError: Cannot read property 'nativeElement' of undefined
我需要获取div容器的宽度,以设置SVG的viewbox。
这是模板:
<div id="what-is-the-width" class="svg-chart-container">
<svg [innerHTML]="svg"></svg>
</div>
带有在此情况下所需内容的 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();
}
}
有人有想法如何让这个工作吗?