I build a tooltip with Angular 5.2.0 and ngrx. When the state updates, the tooltip gets (among other things) an ElementRef to the Element on which it should append (= target). With this target, I can place absolute position the Tooltip:
let rect = state.tooltip.target.nativeElement.getBoundingClientRect();
if (rect) {
this.position.left = rect.left;
this.position.top = rect.top;
}
state.tooltip.target
is of type ElementRef which the element opening the Tooltip gets via @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;
}
with the reference in the template:
<a #linkWithTooltip href="">Lorem</a>
as described here (and in lots of other places).
However, to be able to position the tooltip properly, I have to know the tooltip's size after rendering (for example to center it). What I need is an ElementRef of the Tooltip itself instead of a ViewChild.
How can I get the dimensions of the current component? Can I retrieve them via the Component's ElementRef? And if yes, how do I get the ElementRef?
So if you want to get ElementRef from the child that is angular2 component ( VerticeControlComponent ) you need to explicitely tell using read: ElementRef : @ViewChild('scaleControl', {read: ElementRef}) scaleControl: ElementRef; And then inside ngAfterViewInit hook or later you can write this. scaleControl.
We first import ElementRef from the @angular/core package, next we inject it via the directive's constructor. Next, in the ngOnInit method of the directive we use the nativeElement interface of ElementRef to access the native style property of the DOM element to which the directive is applied.
Add a template reference variable to the component HTML element. Import @ViewChild decorator from @angular/core in component ts file. Use ViewChild decorator to access template reference variable inside the component.
Steps:Use template reference and ViewChildren() to get HTML element. Inject Renderer and ElementRef into the constructor. Use the removeChild() method of the renderer to remove the child component. To get the host element, we need to use ElementRef.
You can use the dependency injection.
import { Component, ElementRef } from '@angular/core';
@Component({ selector: 'tooltip' })
class TooltipComponent {
constructor(private ref: ElementRef) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With