Finding the width of a div element in Angular 2

I have encountered several posts, but none of them quite achieve what I am trying to do. I am dealing with a table that exceeds the width of the page and, due to certain requirements, I need to measure its width.

I attempted:

@ViewChild('tableToMeasure') elementView: ElementRef;

And then added #tableToMeasure to the table. However, this resulted in an error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

Even though it works only on the parent div of the page.

Any suggestions? I need to determine its width both on page load and when the page is resized, and adjust another div's width accordingly.

Answer №1

@Component({
    selector: 'custom-selector',
    template: `<button #tableToCalculate>Press here</button>`
})
export class CustomComponent implements AfterViewInit {

    @ViewChild('tableToCalculate') elementView;

    constructor() {
    }

    ngAfterViewInit() {
        console.log(this.elementView.nativeElement);
    }
}

Answer №2

elementView won't be assigned until ngAfterViewInit has been executed. If your code is in the ngOnInit method or constructor, you will encounter this issue.

Answer №3

I encountered a similar issue and was able to resolve it quite easily. The reason you are getting an 'undefined' error is because the identifier 'tableToMeasure' is not defined in your HTML file.

To fix this, simply include #tableToMeasure within your HTML element.

Here's an example of how you can structure your HTML code:

<div #tableToMeasure style="width: 100px; height: 100px">
   <span>Some content!</span
</div>

In your TypeScript file, make sure to add the following line:

@ViewChild('tableToMeasure')elementView: ElementRef;

Don't forget to import ViewChild and ElementRef from @angular/core.

Best of luck with your implementation!

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

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Error in Angular Apollo V3: Jest unable to locate module 'apollo-angular'

After recently updating angular apollo from version 2.6.0 to v3.0.0, my tests have been broken. I use jest for unit testing, and although the application compiles and runs without any issues, my tests cannot import any dependencies from 'apollo-angul ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Demonstration of basic geometric shapes being generated using Forge Viewer Angular

Using the ng2-adsk-forge-viewer library in Angular 7, I am attempting to render a .dmg file within the browser and create a custom geometry on the view. After creating an Extension and adding the addToScene method, while the Extension runs successfully, I ...

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

Innovative coding solution to modify designated variables in Angular 2 and beyond

Currently, it is possible to utilize the final script of the user which has the ability to modify certain variables that were previously accessible. I have created a simple example in vanilla JavaScript and now I am looking to achieve the same functionali ...

Encountering Compilation Error in @microsoft/mgt Graph Toolkit Upon Transition from Angular 11 to Angular 13

Previously, I had integrated the Microsoft toolkit into my Angular 11 application without any issues. However, when I was asked to upgrade to Angular 13 and updated the toolkit to its latest version (2.3.2 at the time of writing), I started encountering co ...

Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you. Error 1: There is an issue with converting type '({ Id: string ...

Ensure Standardized Schema Type in Universal Restriction

Is it feasible for Zod to mandate that the type of a passed schema is restricted to a basic schema? I may be completely off track here, but I hope my intentions are clear in the provided example. Many thanks. import { ZodType, z } from "zod"; c ...

Modify table cell content based on boolean value - HTML

Currently, I am working with a table that displays properties from an object. Is there a simple method to change the text displayed in a cell instead of the true/false values it is currently set to? For example, one of the columns indicates whether the ob ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...

Searching for a data grid component in Angular 2

I am currently searching for a table-ui-control in Angular 2, but unfortunately, I have not been able to find one that meets my requirements! Here are the features I am looking for in a grid/table: Ability to handle remote data/sorting/filtering Fil ...

Distinguishing between the practical aspects of directly subscribing to an Observable versus employing the subscribe() method with a parameter

I have a function that provides data in an Observable: getData (): Observable<Data[]> {...} To utilize this data in my template and ensure the template remains "live" based on the Observable, I have come across two methods. I created a Subject ins ...

You cannot assign multiple properties with the same name to an object literal

I am facing an issue with two validator functions in my TypeScript file. The first validator checks if a user enters a new password same as the old one, displaying an error if so. The second validator ensures that "new password" and "confirm password" must ...

What is the best way to iterate through an object of objects in Vue.js using mapping?

I am looking to develop a function that maps different items to specific color thresholds. Here is an example of what I have in mind: export const mapMetricsToValue: any = { item1: { 0: 'green--text', 0.3: 'red--text&apo ...

When aot is enabled, ngClass and ngIf condition may not compile successfully

I am encountering an issue with a div using ngClass and ngIf conditions: <div [ngClass]="{ 'active': nbActive === 1 }" > <!-- some stuff --> </div> There is also a similar div using a ngIf condition: <div *ngIf="nbActi ...

efficiently managing errors in a Nest Jest microservice with RabbitMQ

https://i.sstatic.net/sUGm1.png There seems to be an issue with this microservice, If I throw an exception in the users Service, it should be returned back to the gateway and then to the client However, this is not happening! The client only sees the de ...

Update the reducer with accurate data typing

I followed the instructions in the documentation to create a replace reducer, but I encountered an issue while using typescript with redux. The docs do not provide any examples on how to properly type the replace reducer. I tried my own method, but it ende ...

Encountering a deadly mistake with LNK1181 while attempting to npm install web3

On my Windows system, I attempted to install the web3 node package using npm install. I followed the necessary steps by first installing Windows build tools: npm install --global --production windows-build-tools This command executed without issues, but ...

Utilizing Asp.Net for Developing Microservices

Upon digesting this insightful article, I was inspired to consider transitioning our platform to a microservices architecture. Currently, our server stack consists of Asp.Net Web API (Rest...) and Angular 2 on the front end. To test the waters, I wanted ...