所以我有一个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 回答
请在
ngAfterViewInit()
内运行blah()
,因为在ngOnInit()
生命周期挂钩时不会呈现视图 .为此添加了stackblitz代码 .