如何在页面加载后获得Angular 4中的(DOM)元素的宽度

mpr*_*pro 7 javascript typescript angular

我正在寻找Angular 4中的解决方案来获取DOM元素的宽度而不采取任何操作(单击或窗口调整大小),只是在页面加载后,但在我开始绘制svg之前.我在这里找到了类似的案例,但它对我不起作用.我犯了同样的错误:

错误TypeError:无法读取未定义的属性"nativeElement"

我需要获取div容器的宽度来设置svg的veiwbox我正在其中绘制.

这是模板:

<div id="what-is-the-width" class="svg-chart-container">
    <svg [innerHTML]="svg"></svg>
</div>
Run Code Online (Sandbox Code Playgroud)

和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();
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有人有想法如何让这个工作?

小智 16

在加载页面之前,您不能拥有元素的大小.如果不够清楚,如果未加载页面,则不会加载HTML元素.

如果要根据div设置SVG的视图框,则需要等待页面加载,然后更改视图框.这是完全可行的.

最快的方法是:

<div #container>Container's width is {{ container.offsetWidth }}</div>
<svg:svg [width]="container.offsetWidth"></svg>
Run Code Online (Sandbox Code Playgroud)

我会让你处理viewBox属性,因为我真的不知道你想用它做什么.

svg:顺便说一下,你需要添加前缀来告诉angular它不是自定义指令.

  • `@ViewChild('container')容器:ElementRef;`是声明.要获得该值,它是`this.container.nativeElement.offsetWidth`.对于你的ide,你可以使用`(this.container.nativeElement as HTMLElement).offsetWidth`. (4认同)

Dyl*_*sky 5

如果有人需要其他解决方案:

const myElement = document.getElementById('element');

if(myElement){
  myElement.getBoundingClientRect().width; // Get the width of the your element
}
Run Code Online (Sandbox Code Playgroud)