Is it not possible to access the width and height of an element using ViewChild, unlike what is suggested in other responses

I've encountered an issue with my Angular component. The HTML code for the component, before any TypeScript is applied, looks like this:

<svg #linechart id="chartSpace"></svg>

Wanting to create a responsive webpage featuring a line chart, I attempted to set the height and width based on the view like so:

#chartSpace { width: 100vw; height: 50vh; }

In order to scale the chart's axes using the obtained height and width, I followed examples from Stack Overflow and tried accessing the element with ViewChild in my TypeScript file. Unfortunately, when running the code, the height and width are logging as undefined. What could I be overlooking?

Here's the TypeScript 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);
  }
}

Answer №1

For proper rendering, it is recommended to execute the blah() function within the ngAfterViewInit() method rather than in the 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}
}

Check out the code example on StackBlitz.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular's *ngIf directive in conjunction with Observables to handle data retrieved from

Utilizing multiple REST services for data retrieval and altering the value of an Observable in my component code has been a challenge. I've attempted to use *ngIf to toggle the visibility of div tags based on the result, however, the Observable's ...

The Ngrx selector fails to activate when the reducer modifies the portion

In my Angular 2 application, I heavily utilize Ngrx stores which have proven to be extremely beneficial. I have a well-structured system in place for my stores where I use selectors to retrieve specific parts of the state. Normally, all the selectors work ...

Despite encountering the 'property x does not exist on type y' error for Mongoose, it continues to function properly

When working with Mongoose, I encountered the error TS2339: Property 'highTemp' does not exist on type 'Location' when using dot notation (model.attribute). Interestingly, the code still functions as intended. I found a solution in the ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Setting up an Angular development environment without relying on the CLI framework

I've been diving into learning Angular and experimenting with demo apps, but I'm finding it difficult to get a clear understanding of how everything works and the underlying concepts. Most resources I come across emphasize using CLI for automatio ...

What is the best way to make the current tab stand out?

I have implemented a TabHeader component to create a dynamic Tab Menu that displays table contents based on months. The loop runs from the current month back to January, and the content is updated dynamically through an API call triggered by changes in the ...

Set the values retrieved from the http get response as variables in an Angular application

Lately, I've been working on a settings application with slide toggles. Currently, I have set up local storage to store the toggle state. However, I now want to update the toggle status based on the server response. The goal is to toggle buttons accor ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

Issue with the functionality of Angular reactive custom validator inoperable

Recently, I created a simple validator that compares the values of two date form controls within a form group. The basic rule is that the maturityDate has to be greater than the valueDate, otherwise the form group should be marked as invalid. Here is how ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

To properly display a URL on a webpage using Angular, it is necessary to decode

After my console.log in Angular 5 service call to the component, I can see the correct data URL being displayed http://localhost:4200/inquiry?UserID=645 However, when it is inside an Angular for loop in the HTML template, it displays http://localhost:42 ...

Problem Encountered with Inaccurate Binding of Dynamic Form Control Values in Angular

UPDATE: Follow this link to access the editor for my Stackblitz application, which demonstrates a simplified version of the issue regarding the "transfer" of value between the first and second controls. I am currently developing a dynamic form in Angular ...

Angular Material Progress Spinner is static and not animated

I've been attempting to incorporate an indeterminate spinner from Angular Material. After reviewing the stack blitz example provided on their official website https://stackblitz.com/angular/nkabnxaenep, I carefully compared the package jsons and could ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type '(( ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...