【问题标题】:How to get width of (DOM) Element in Angular 4 after page is loaded加载页面后如何在Angular 4中获取(DOM)元素的宽度
【发布时间】:2018-02-09 14:33:27
【问题描述】:

我正在寻找 Angular 4 中的解决方案来获取 DOM 元素的宽度,而无需执行任何操作(单击或调整窗口大小),就在页面加载之后,但在我开始绘制 svg 之前。我在here 中发现了一个类似的案例,但它对我不起作用。我得到同样的错误:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

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

这是模板:

<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();
  }
}

有人知道如何让它工作吗?

【问题讨论】:

  • 引用名称中好像不允许使用“-”,刚刚得到Uncaught Error: Template parse errors

标签: javascript angular typescript


【解决方案1】:

在页面加载之前,您不能拥有元素的大小。如果还不够清楚,如果页面没有加载,那么你的 HTML 元素就没有加载。

如果你想根据一个div来设置你的SVG的viewbox,你需要等待页面加载,然后改变viewbox。这是完全可行的。

最快的方法是:

<div #container>Container's width is {{ container.offsetWidth }}</div>
<svg:svg [width]="container.offsetWidth"></svg>

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

顺便说一句,您需要添加 svg: 前缀来告诉 Angular 这不是自定义指令。

【讨论】:

  • 太简单了! :) 谢谢,它的工作原理!我将编辑标题和问题,因为它确实不清楚。我的意思当然是在页面加载之后但在我触发方法绘制 svg 之前获取宽度。
  • 没问题!记得将您的问题也标记为已解决!
  • @ViewChild('container') container : ElementRef; 是声明。要获取值,它是this.container.nativeElement.offsetWidth。对于您的 ide,您可以使用 (this.container.nativeElement as HTMLElement).offsetWidth
  • 哦,你需要在生命周期钩子的init步骤之后使用nativeElement。这意味着不在构造函数中,但至少在ngOnInit 中!
  • 如果你得到“无法绑定到 'width' 因为它不是 ':svg:svg 的已知属性”,请使用:
猜你喜欢
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 2017-10-02
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多