无法像此处的其他答案一样通过 ViewChild 检索元素的宽度和高度?
Cannot retrieve width and height of an element through ViewChild like other answers here do?
所以我有一个 Angular 组件,在打字稿涉及之前的 HTML 很简单:<svg #linechart id="chartSpace"></svg>
为了制作一个具有折线图的响应式网页,我决定根据视图设置高度和宽度:#chartSpace { width: 100vw; height: 50vh; }
然后为了获得用于缩放图表轴的 height/width,我按照 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);
}
}
请在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 代码。
所以我有一个 Angular 组件,在打字稿涉及之前的 HTML 很简单:<svg #linechart id="chartSpace"></svg>
为了制作一个具有折线图的响应式网页,我决定根据视图设置高度和宽度:#chartSpace { width: 100vw; height: 50vh; }
然后为了获得用于缩放图表轴的 height/width,我按照 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);
}
}
请在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 代码。