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 Mongoose Typescript 2 Schema with fields referencing one another in different schemas

I'm currently facing an issue as I attempt to define 2 schemas in mongoose and typescript, where each schema has a field that references the other schema. Here's an example: const Schema1: Schema = new Schema({ fieldA: Number, fieldB: Sch ...

Uploading files using Angular 6 to communicate with a Flask (Python) API

I have developed a web service using Flask to save files, following the example provided in the official Flask documentation: @app.route('/parse_table', methods=['POST']) def upload_file(): print(request.files) # check if the p ...

How to effectively close an Angular material dialog with active ngForm?

Is it possible to close a dialog when using ngForm? I have multiple dialogs that appear before the final one, and I know how to get data using [mat-dialog-close]="true" along with MAT_DIALOG_DATA. However, in this last dialog, I am using ngForm t ...

Stop/continue a stopwatch Observable

I'm trying to create a basic stopwatch using angular/rxjs6. I've managed to start the timer, but I'm struggling with pausing and resuming it. source: Observable<number>; subscribe: Subscription; start() { this.source = tim ...

The connection to Socket IO was refused due to a network error (net::

As I work on integrating socket.io into my application hosted on Azurewebsites, webapp I have the following server.js setup: var app = require('express')(); var server = require('http').createServer(app); server.listen(process.env.PO ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Execution of the RxJS pipe Finalize operator initiated prior to Observable finalization

After updating the detailed information of users, I attempted to retrieve the updated user list. Initially, I used this.mediaService.updateImports(): Observable<any> to update the user details. Next, I tried displaying the updated user details us ...

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

Challenge Encountered while Generating Angular Docker Image using VSTS Pipeline

I'm currently in the process of setting up a VSTS pipeline to create a Docker Image for an Angular Application. I've chosen the "Hosted Windows Container" as the Agent pool, but I'm encountering the following error: Step 1/5: FROM nginx:alp ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Translate language in an Angular file using TypeScript

const typeArray= [ { id: 'PARENT', name: '{{ appConstants.type.PARENT | translate }}' }]; What is the best way to incorporate translations when declaring an array in a TypeScript file? ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

Navigating through different views in Angular 2 using UI Router and ng2 routing directly from

I am currently utilizing the UI-Router ng2 and attempting to change routes after a certain function is triggered. My code snippet looks like this: SomeFunction() { if(condition){ router.navigate(['/newRouteName']); } } It's ...

Typing in a number will always activate the change event

Having trouble with Angular's change event on numeric input? It doesn't always trigger when clicking the increment or decrement buttons - it only triggers once and then requires the input to lose focus before triggering again. Is there a way to ...

Disabling sound feature in the "mat-video" npm package

Currently, I've implemented the mat-video package (npm i mat-video) in my angular application to facilitate video playback. It's been working quite well. <mat-video style="min-height: 30%" quality="false" title="My Tutorial Title" loo ...

Changing the color of the pre-selected date in the mat-datepicker Angular component is a key feature that can enhance the

Is there a way to adjust the color of the preselected "today" button in mat-datepicker? https://i.stack.imgur.com/wQ7kO.png ...

What is the recommended approach for returning two different types in a TypeScript function?

My API function currently performs a post request and returns an Observable of ModelAResponse, which is an interface I have defined. I now want to modify this function so that it can return an Observable of either ModelAResponse or ModelBResponse based on ...