Dealing with Angular in this situation, my goal is to have an image or video displayed inside a tooltip when hovering over specific content. However, there seems to be a flickering effect before the image renders, making the transition less smooth compared to using text instead of an image. How can I resolve this issue?
I am attempting to set the image source within an input for the tooltip component. The code snippet below demonstrates how this is implemented:
app.component.html
<button awesomeTooltip="Hello World!" image="https://imgplaceholder.com/420x320/ff7f7f/333333/fa-image">Hi there, I have a tooltip</button>
tooltip.component.ts
import { Component, Input } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'awesome-tooltip',
styleUrls: ['./tooltip.component.css'],
templateUrl: './tooltip.component.html',
animations: [
trigger('tooltip', [
transition(':enter', [
style({ opacity: 0 }),
animate(300, style({ opacity: 1 })),
]),
transition(':leave', [
animate(300, style({ opacity: 0 })),
]),
]),
],
})
export class AwesomeTooltipComponent {
@Input() image=''
@Input() text = '';
}
tooltip.component.html
<div @tooltip>
<img [src]="image" width="20px" height="30px">
<!-- Hello -->
</div>
tooltip.directive.ts
import { ComponentRef, Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
import { Overlay, OverlayPositionBuilder, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { AwesomeTooltipComponent } from './tooltip.component';
@Directive({ selector: '[awesomeTooltip]' })
export class AwesomeTooltipDirective implements OnInit {
@Input('awesomeTooltip') text = '';
@Input('image') image = '';
private overlayRef: OverlayRef;
constructor(private overlay: Overlay,
private overlayPositionBuilder: OverlayPositionBuilder,
private elementRef: ElementRef) {
}
ngOnInit(): void {
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions([{
originX: 'center',
originY: 'top',
overlayX: 'center',
overlayY: 'bottom',
offsetY: -8,
}]);
this.overlayRef = this.overlay.create({ positionStrategy });
}
@HostListener('mouseenter')
show() {
const tooltipRef: ComponentRef<AwesomeTooltipComponent>
= this.overlayRef.attach(new ComponentPortal(AwesomeTooltipComponent));
tooltipRef.instance.text = this.text;
tooltipRef.instance.image = this.image;
}
@HostListener('mouseout')
hide() {
this.overlayRef.detach();
}
}
The stackblitz link can be accessed here:
The desired outcome includes:
- The ability to pass an image URL through the tag on which the tooltip should appear.
- The tooltip displaying the specified image within it.