Reputation: 40
So I've got an Angular component, the HTML of which before the typescript gets involved is simply: <svg #linechart id="chartSpace"></svg>
In an attempt to make a responsive webpage featuring a line chart, I decided to set the height and width with respect to the view: #chartSpace { width: 100vw; height: 50vh; }
Then to get the height/width for scaling the chart's axes, I followed several examples here on Stack Overflow and tried obtaining the element with ViewChild, as seen below. However, running this results in height and width being logged as undefined. What am I missing?
TS file:
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);
}
}
Upvotes: 0
Views: 2797
Reputation: 864
Please run blah()
inside ngAfterViewInit()
because view will not be rendered at the time of ngOnInit()
lifecycle hook.
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}
}
Added stackblitz code for this.
Upvotes: 4