Is it possible to show a custom component as a tooltip?

53 Views Asked by At

The designed tooltip I have to work with is very complex. Is there a way for me to make a new component, and use that as the tooltip?

2

There are 2 best solutions below

0
codewithharshad On
import { Component } from '@angular/core';
import { NgbTooltipConfig } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-my-component',
  template: `
    <button type="button" [ngbTooltip]="tooltipContent" placement="top">Hover over me!</button>
    <ng-template #tooltipContent>
      <app-tooltip-content></app-tooltip-content> <!-- Your component goes here -->
    </ng-template>
  `,
  providers: [NgbTooltipConfig] // Add this if not already provided in your app
})

export class MyComponent {
  constructor(config: NgbTooltipConfig) {
    config.autoClose = 'outside'; // You can configure tooltip behavior here
  }
}
0
Bhavy Ladani On

As far as I think, creating a component to display your custom tooltip might not be the most effective solution though it is completely possible.

I had been in this state in past and what I found best and applied in my project was to create a directive and import in the components where it is needed. Import the directive in ts file and use in HTML file.

I am attaching the example below and you can make changes as per your requirements.

Directive:

import {
  Directive,
  ElementRef,
  HostListener,
  Input,
  OnInit,
} from "@angular/core";

@Directive({
  selector: "[useTooltip]",
  standalone: true,
})
export class TooltipDirective implements OnInit {
  @Input() tooltip: string = "";
  @Input() tooltipPlacement: "top" | "left" | "bottom" | "right" = "top";
  tooltipElement: HTMLElement | undefined;
  constructor(private el: ElementRef) {}

  ngOnInit(): void {
    const element = this.el.nativeElement as HTMLElement;

    let nativeTooltip = element.getAttribute('tooltip');
    if(nativeTooltip) {
      this.tooltip = nativeTooltip;
    }
    if (!this.tooltip.length ) return;

    element.style.position = "relative";

    const tooltipElem = document.createElement("span");
    tooltipElem.classList.add("cust-tooltip");
    tooltipElem.classList.add("tooltip-" + this.tooltipPlacement);
    this.tooltipElement = tooltipElem;

    tooltipElem.innerText = this.tooltip;

    element.appendChild(tooltipElem);
  }

  @HostListener("mouseenter", ["$event"])
  onMouseEnter(event: MouseEvent) {
    this.tooltipElement.style.opacity = "1";
  }

  @HostListener("mouseleave", ["$event"])
  onMouseLeave(event: MouseEvent) {
    this.tooltipElement.style.opacity = "0";
  }
}

Now when you want to use it in any component, import it in its module file and use it in HTML component as its attribute and data you want to show it in tooltip.