页面加载后如何在Angular 4中获取(DOM)元素的宽度 [英] How to get width of (DOM) Element in Angular 4 after page is loaded

查看:734
本文介绍了页面加载后如何在Angular 4中获取(DOM)元素的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Angular 4中的解决方案,以便在加载页面之后但在开始绘制svg之前,无需采取任何操作(单击或调整窗口大小)即可获得DOM元素的宽度.我在此处找到了类似的情况,但是没有为我工作.我收到相同的错误:

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 here but it doesn't work for me. I get the same error:

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

ERROR TypeError: Cannot read property 'nativeElement' of undefined

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

I need to get the width of div container to set veiwbox of svg I'm drawing inside it.

这是模板:

<div id="what-is-the-width" class="svg-chart-container">
    <svg [innerHTML]="svg"></svg>
</div>

和TS文件,在这种情况下需要填充:

and TS file with stuff needed in this case:

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?

推荐答案

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

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.

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

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 #container>Container's width is {{ container.offsetWidth }}</div>
<svg:svg [width]="container.offsetWidth"></svg>

我将让您处理viewBox属性,因为我真的不知道您想如何使用它.

I'll let you deal with the viewBox attribute, since I don't really know what you want to do with it.

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

You need to add the svg: prefix to tell angular it's not a custom directive, by the way.

这篇关于页面加载后如何在Angular 4中获取(DOM)元素的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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