簡體   English   中英

如何在加載頁面后獲取 Angular 4 中 (DOM) 元素的寬度

[英]How to get width of (DOM) Element in Angular 4 after page is loaded

我在 Angular 4 中尋找解決方案,無需采取任何操作(單擊或 window 調整大小)即可獲取 DOM 元素的寬度,就在頁面加載之后,但在我開始繪制 svg 之前。我發現了一個類似的案例在這里,但它對我不起作用。 我犯了同樣的錯誤:

錯誤 TypeError:無法讀取未定義的屬性“nativeElement”

我需要獲取 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();
  }
}

有沒有人知道如何讓它工作?

在加載頁面之前,您不能擁有元素的大小。 如果不夠清楚,如果未加載頁面,則不會加載HTML元素。

如果要根據div設置SVG的視圖框,則需要等待頁面加載,然后更改視圖框。 這是完全可行的。

最快的方法是:

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

我會讓你處理viewBox屬性,因為我真的不知道你想用它做什么。

順便說一下,你需要添加svg:前綴來告訴angular它不是自定義指令。

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

 <div id="element"></div>

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

if(myElement){
  myElement.getBoundingClientRect().width; // Get the width of the your element
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM