programing

페이지 로드 후 Angular 4에서 (DOM) Element의 너비를 가져오는 방법

lastcode 2023. 6. 21. 22:38
반응형

페이지 로드 후 Angular 4에서 (DOM) Element의 너비를 가져오는 방법

페이지를 로드한 직후이지만 svg를 그리기 시작하기 전에 아무런 작업(클릭 또는 창 크기 조정) 없이 DOM 요소의 너비를 얻을 수 있는 Angular 4에서 해결책을 찾고 있습니다.여기서 비슷한 케이스를 찾았지만 저한테는 안 통합니다.동일한 오류가 발생합니다.

오류 유형 오류: 정의되지 않은 'nativeElement' 속성을 읽을 수 없습니다.

내가 그 안에 그리는 svg의 viewbox를 설정하기 위해 div 컨테이너의 너비를 얻어야 합니다.

템플릿은 다음과 같습니다.

<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 속성을 처리할 수 있도록 하겠습니다. viewBox 속성으로 무엇을 하고 싶은지 잘 모르기 때문입니다.

다음을 추가해야 합니다.svg:그나저나, 그것은 사용자 지정 지시가 아니라는 것을 각도를 알려주는 접두사입니다.

다른 솔루션이 필요한 경우:

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

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

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

언급URL : https://stackoverflow.com/questions/48708119/how-to-get-width-of-dom-element-in-angular-4-after-page-is-loaded

반응형