1

I have an Angular 6 application that displays a grid of objects of different type. I'd like that, when a user moves the mouse over an object for a while (300ms for example), a tooltip appeared with more information about that object. I'm using PrimeNG UI library, that comes with a handy tooltip component, that can be used like this:

<div class="divObject" 
  pTooltip="<h2>Object info</h2><p>Here would go the object information</p>" [escape]="false"
  tooltipPosition="top">
    <!-- OBJECT NAME -->
</div>

The problem I have is that, to get the info about the object, I need to make a call to the DB server. So, I considered creating a pipe to get the data, and use it like:

<div class="divObject"
  pTooltip="{{ object | getInfoPipe }}" [escape]="false"
  tooltipPosition="top">
  <!-- OBJECT NAME -->
</div>

But, I've read that using pipes for API calls is a really bad idea because it can be called tens of times, so it would overload the server rapidly.

How could I achieve what I need? (Not necessarily using the PrimeNG tooltip component, I'm open to other alternatives)

Thanks!

Fel
  • 4,428
  • 9
  • 43
  • 94
  • Hope this link help you: [Primeng pTooltip loop](https://stackoverflow.com/questions/49755193/primeng-ptooltip-loop?answertab=active#answer-49756070) – Sanoj_V May 11 '18 at 13:21
  • Hi! I've checked the link but I can't use the example in it because it would do as many API calls as objects in the grid, and I only want to call to the API for the hovered object. Thanks anyway! – Fel May 11 '18 at 14:47

1 Answers1

0

There are different approaches to this.

You can make the pipe execute the call only one for a given input by making it pure: https://stackoverflow.com/a/39285608/4125622

You could make an interceptor cache HTTP-requests and respond to same requests with the same response without calling the actual backend: https://angular.io/guide/http#intercepting-requests-and-responses

But you are right, both approaches are a bit hacky.

I would bind the tooltip-info to a variable (like object.tooltipText, see example below) and disable the tooltip as long as it is undefined (not loaded from server yet). In this case you would need to trigger the HTTP-call yourself; you could do this by calling httpClient in the ngOnInit of the component which holds the element with the specific tooltip. If you use Redux, you would only dispatch an action and the reducer would update your object like this:

object.mainText: "click me",
object.tooltipText: undefined

becomes

object.mainText: "click me",
object.tooltipText: "for more information see example.org"

As for the tooltip-recommendation, I recommend ngx-bootstrap one. The lib is a bit more active and the developers are not as rude as the prime-ng ones (who are known for closing issues without reasons).

Phil
  • 7,065
  • 8
  • 49
  • 91