首页 文章

无法通过ViewChild检索元素的宽度和高度,就像这里的其他答案一样吗?

提问于
浏览
0

所以我有一个Angular组件,在打字稿之前的HTML就是: <svg #linechart id="chartSpace"></svg>

为了创建一个以折线图为特色的响应式网页,我决定相对于视图设置高度和宽度: #chartSpace { width: 100vw; height: 50vh; }

然后为了获得用于缩放图表轴的高度/宽度,我在Stack Overflow上遵循了几个示例并尝试使用ViewChild获取元素,如下所示 . 但是,运行此操作会导致高度和宽度记录为未定义 . 我错过了什么?

TS档案:

import {Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component ({
  selector: 'app-line-chart',
  templateURL: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
  @ViewChild("linechart") elementView: ElementRef;
  height: number;
  width: number;
  constructor() {}
  ngOnInit() {
    this.blah();
  }
  blah() {
    this.height = this.elementView.nativeElement.offsetHeight;
    this.width = this.elementView.nativeElement.offsetWidth;
    console.log("height: " + this.height + " and width: " + this.width);
  }
}

1 回答

  • 3

    请在 ngAfterViewInit() 内运行 blah() ,因为在 ngOnInit() 生命周期挂钩时不会呈现视图 .

    ngAfterViewInit() {
        this.blah();
    }
    
    blah() {
        let dimension = this.elementView.nativeElement.getBoundingClientRect();
        console.log(dimension); // {"x":8,"y":8,"width":578,"height":163.5,"top":8,"right":586,"bottom":171.5,"left":8}
    }
    

    为此添加了stackblitz代码 .

相关问题