What is the process for obtaining a Component's ElementRef in order to access the BoundingClientRect of that specific Component?

I have successfully created a tooltip using Angular 5.2.0 and ngrx. The tooltip, among other things, receives an ElementRef to the target Element when the state updates, allowing me to position it absolutely:

let rect = state.tooltip.target.nativeElement.getBoundingClientRect();
if (rect) {
  this.position.left = rect.left;
  this.position.top = rect.top;
}

The state.tooltip.target is of type ElementRef and is obtained by the element triggering the tooltip through @ViewChild:

@ViewChild('linkWithTooltip') tooltipTarget: ElementRef;

openTooltip() {
    if (this.tooltipOpen) {
      this.tooltipAction.closeTooltip();
    } else {
      this.tooltipAction.openTooltip({
        text: 'foo',
        target: this.tooltipTarget
      });
    }
    this.tooltipOpen = !this.tooltipOpen;
}

This is referenced in the template as:

<a #linkWithTooltip href="">Lorem</a>

As explained here and in other sources, I am able to position the tooltip properly. However, to accurately position the tooltip, I need to know its dimensions after rendering, such as for centering it. I require an ElementRef of the Tooltip itself rather than a ViewChild.

How can I obtain the dimensions of the current component? Can I retrieve them using the Component's ElementRef? If so, how can I access the ElementRef?

Answer №1

Utilizing dependency injection can greatly enhance your code organization.

import { Component, ElementRef } from '@angular/core';

@Component({ selector: 'tooltip' })
class TooltipComponent {
   constructor(private ref: ElementRef) {}
}

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

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...

Working with undefined covariance in TypeScript

Despite enabling strict, strictNullChecks, and strictFunctionTypes in TypeScript, the following code remains error-free. It seems that TypeScript is not catching the issue, even though it appears to be incorrectly typed. abstract class A { // You can p ...

Tips for managing 'single click' and 'double click' events on a specific html element in typescript:Angular 2 or 4

My problem lies in the fact that both events are activated when I double click. For instance, I want distinct functionality to occur for each event trigger. <a (click)="method1()" (dblclick)="method2()"> Unfortunately, both method1() and method2() ...

Excessive recursion detected in the HttpInterceptor module

My application uses JWT tokens for authentication, with a random secure string inside the JWT and in the database to validate the token. When a user logs out, a new random string is generated and stored in the database, rendering the JWT invalid if the str ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

Customizing the appearance of a form control in response to its value in Angular's Reactive

I have a unique query regarding formatting text related to formControl in an application where the formControls are created using FormBuilder and arrays of formControls. This inquiry involves retrieving the current value of a formControl and altering the ...

Adding comments in TypeScript: A quick guide

Hey there, I'm new to TS and could use some help. Here is the code snippet I have: I want to comment out the logo but adding "//" and '/*' doesn't seem to work. This is what I tried: // <LogoComponent classes={{container: style.log ...

Displaying the ngFor data in the HTML section

Struggling with passing an array from poll-vote.component.ts to poll-vote.component.html. The data involves radio buttons and I'm using ngFor loop with index, but it's not working as expected: Here is my poll-vote.component.ts code: import { Com ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Tips for utilizing array.items in joiful validation?

Can someone provide an example code or a link on how to correctly use the joyful validation for array items? I attempted the array.items validation code using joyful, but I am not sure how to specify the items. Thanks in advance! ...

The Angular Material Dialog refuses to close

I am facing a unique problem where my MatDialog component, once opened, refuses to close in my Angular application. The calling component uses SVG instead of HTML as the view, which seems to be causing some handling issues. Unfortunately, I have been unabl ...

Error Encountered: Unable to locate control within nested form array: 'module -> 0 -> view'

I am creating a Form Array with Nesting, using Reactive Forms in Angular 7. I am encountering this error: ERROR Error: Cannot find control with path: 'module -> 0 -> view' I have built the Nested Form but keep getting errors. Please help m ...

The Angular tag <mat-expansion-panel-header> fails to load

Every time I incorporate the mat-expansion-panel-header tag in my HTML, an error pops up in the console. Referencing the basic expansion panel example from here. ERROR TypeError: Cannot read property 'pipe' of undefined at new MatExpansionPanel ...

Why does my export function get executed every time the TextInput changes?

Hey there, here is my React and TypeScript code. I'm wondering why the console.log statement gets called every time my text field changes... export default function TabOneScreen({ navigation, }) { const [out_1, set_out1] = useState('' ...

What is the process of extracting an observable from another observable using the pipe method?

Is there a more efficient way to convert an Observable of Observables into an array of Observables in my pipe method? Here is the scenario: // The type of "observables" is Observable<Observable<MyType>[]> const observables = this.http.get<M ...

Customize the theme type with @mui/system

Is there a way to customize my theme settings in @mui/system? While using the sx prop in Stack, the theme is defined in createTheme.d.ts, but it seems like there isn't an option to extend or override it. To work around this limitation, I have been u ...

What could cause my arguments to "not align with any signature" of console.log?

Here is a basic class example: export class Logger { constructor(private name: string) {} debug(...args: any[]) { console.debug(...args) } log(...args: any[]) { console.log(...args) } } Despite being able to pass anything to console.l ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...