Tooltip not working inside a tag with ngFor attribute

Issue

Could someone explain to me why the tooltip in this piece of code using Angular 4 templates doesn’t work?

<template ngFor let-channel [ngForOf]="channels">
  <td>
    <em *ngFor="let color of findBallsColor()" class="fa fa-circle {{ color }}" [tooltip]="id"></em>
  </td>
</template>
<ng-template #id>
  test
</ng-template>

If I remove the *ngFor inside the <em> tag it works fine (showing just one element obviously). I’m quite new to Angular so probably I’m missing some understanding of how it really works here.

EDIT

I found out the problem comes from the type returned from the Typescript function. In the code above, the list returned by findBallsColor() is actually an object that contains 4 fields. When I change it to just return a string it works. So the code looks similar to this:

HTML:

<template ngFor let-channel [ngForOf]="channels">
  <td>
    <em *ngFor="let color of findBallsColor()" class="fa fa-circle {{ status.color }}" [tooltip]="id"></em>
  </td>
</template>
<ng-template #id>
  test
</ng-template>

TS:

findBallsColor():any[] {
  return [{"statut":"ERROR","name":"name","otherField":"value","anotherField":"value"}];
}

Does anyone know the why of this behaviour?

Solution

I had a similar problem, here’s an excerpt from this Github issue, that details what is wrong with the way you get your data for your *ngFor.


Calling a function from the template is not a good practice and this is an example of why this recommendation exists.

When the tooltip is fired in the first case, it starts an angular detection cycle, which in turn calls items() again and it tries to show the tooltip again and it starts another angular detection cycle and it goes on and on and on repeatedly.

At first, the recommendation exists to avoid performance issues, but it has other consequences like in your case.

If you put a console.log in items(), you’ll see it keeps being called again and again…

If calling a function is mandatory, use a pipe instead.


So, in your code, if you used a pipe or an observable or array of some sort, then your tooltip would work, but currently it just keeps calling the function.

Answered By – Ivar Kallejärv

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.