The offsetWidth of the nativeElement in Angular 2's ElementRef is consistently returning a value

Is there a way to retrieve the width of an element with a dynamic width using Angular 2? I can easily accomplish this with pure javascript, but not through Angular 2.

constructor(private element: ElementRef) {
// ....

Obtaining the width

let width =  this.element.nativeElement.offsetWidth;

console.log('js offset width', document.getElementById('foobar').offsetWidth);
console.log('angular2 offset width', width);

Getting the width through vanilla JavaScript works as expected:

document.getElementById('foobar').offsetWidth 

However, when trying to get the width in Angular 2, it always returns 0. How can I access the offset width using Angular's ElementRef instead?

Answer №1

The TemplateRef is not connected to any of the DOM elements.

@ViewChild('bar') bar: TemplateRef;

Add the following attribute in your HTML:

<div #bar></div>

After implementing this, OnInit will return a non-zero value.

SEE LIVE DEMO

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

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Connecting the output of an *ngFor loop to a universal variable

*ngFor="let item of items | filter:{ name: searchString } : searchString as filteredItems" and then afterwards <button (click)="doSomething(filteredItems)> The variable filteredItems is a local variable that is only accessible within the *ngFor lo ...

Why should we include the '#' character in jhipster URLs?

Standard Angular applications typically do not include a '#' sign in their URLs. However, in JHipster URLs, the '#' character serves a specific purpose. Can you explain the significance of the '#' symbol in JHipster URLs and h ...

Setting input autofocus in a recursive Angular2 component

Currently, I am working on creating a tree view system similar to Workflowy for practice purposes. The simple version is operational; however, I am facing difficulty in setting the input focus when adding a new component. I have experimented with various ...

agm-info-window - Adjusting position to the right

Currently, I am using angular google maps to display maps along with markers and info windows. The issue I am facing is that the info window always appears on top. Is there a way to change its position to the right instead? <agm-map [latitude]="lat" ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

Issue: [HPM] Context not recognized. Please specify a valid context such as: "/api" or ["/api", "/ajax"]

Suddenly, I am encountering the following error in my Angular 7 project without making any changes. Strangely, it was working fine until yesterday. Error: [HPM] Invalid context. Expecting something like: "/api" or ["/api", "/ajax"] at Object.matchContext ...

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

Is Angular9 BehaviorSubject from rxjs giving trouble across different components?

I am facing an issue with updating data in real-time from the profile component to the header component. Initially, it works fine but after updating any value in the profile component, the header observable does not subscribe again. To solve this problem, ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Typescript: Securing Data with the Crypto Module

I am currently working on encrypting a password using the built-in crypto module. Previously, I used createCipher which is now deprecated. I am wondering if there is still an effective way to achieve this. Here is the old code snippet: hashPassword(pass: ...

Using Angular DI to inject a specific token value into a provider factory

Can an InjectionToken be injected into a factory provider? This is what I have implemented: export const HOST_TOKEN = new InjectionToken<string>("host"); let configDataServiceFactory = (userService: UserService, host: string) => { return ne ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Tips for achieving asynchronous data retrieval using Angular Observable inside another Observable

What is my goal? I have several components with similar checks and data manipulation activities. I aim to centralize these operations in an observable. To do this, I created an observable called "getData" within my service... The unique aspect of "getData ...

Angular2 data binding does not update when properties change

I'm struggling to establish the connection between the fields and the component in order for them to update when the properties change in OnDataUpdate(). The field "OtherValue" successfully binds two ways with the input field, and the "Name" field di ...

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...

Troubleshooting Angular 7 Build Failure: Missing Typescript .d.ts Declaration Files for Ahead-of-Time Compilation

I have encountered difficulties in building my Angular 7 application after upgrading from v6. When I use ng build, everything runs smoothly. However, when I try either ng serve --aot, ng build --aot, or ng build --prod (which also includes aot), an error ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

How to handle an empty data response in Angular 2's HTTP service

My ASP.NET web API has a simple method with the following test results: $ curl localhost:5000/Api/GetAllQuestions [{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}] However, I am encountering an issue in my Angular 2 HTTP serv ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...