<ng-container *ngIf="show">
<div #tooltip>
// some elements
</div>
</ng-container>
Say, there's a template like above. I'd like to set position of the tooltip each time a method is called:
export class AComponent {
@ViewChild('tooltip') tooltip: ElementRef;
show: boolean;
constructor(
private renderer: Renderer2
)
methodA(e: MouseEvent): void {
this.show = true;
const tooltip = this.tooltip.nativeElement;
this.renderer.setStyle(tooltip, 'left', e.offsetX - tooltip.offsetWidth + 'px');
}
But when I run this code, I get an error Cannot read property 'nativeElement' of undefined, which I'm guessing DOM hasn't got updated since I reset the show property to true so tooltip property doesn't exist in DOM.
So I had to go with hidden property:
<div #tooltip [hidden]="show">
// some elements
</div>
There's no problem with this way but I'm wondering if there's any other workaround to make it work with *ngIf approach. Any insight would be appreciated!
You can move the style to the template and give it a dynamic value. The calculateLeft method will only be called when a valid #tooltip is in the DOM.
Also notice there is no need for the ViewChild nor Renderer2 in this case:
import {Component} from '@angular/core';
@Component({
...
})
export class AComponent {
show: boolean;
lastOffsetX: number;
public methodA(e: MouseEvent): void {
this.show = true;
this.lastOffsetX = e.offsetX;
}
public calculateLeft(tooltip) {
return (this.lastOffsetX - tooltip.offsetWidth) + 'px';
}
}
And the HTML:
<ng-container *ngIf="show">
<div #tooltip [ngStyle]="{left: calculateLeft(tooltip)}">
Hello
</div>
</ng-container>
<button (click)="methodA($event)">Click me</button>
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