Search code examples
htmlangularangular-materialtooltipinnerhtml

How do I use a variable from another component containing HTML and AngularMaterial Tooltips?


In my Angular project (newest version) I want to display a text containing a tooltip when you hover over it. I use Angular Material for that. For the possible tooltip there are multiple options, so I need a string variable containing some extra HTML and a tooltip. While the extra HTML works with [innerHTML]="variable", the tooltip doesn't. Why is that and how can I fix it?

In component1 I got: <div [innerHTML]="variable"></div>

In component2 I got: let variable = '<span matTooltip="TooltipText"><b>Text</b></span>'

I expect the tooltip and the bold text to work, but only the bold text gets applied, the tooltip isn't there. However when I don't use a variable and just input the content of the variable directly, everything works. So it seems like I just can't apply the tooltip through a variable.


Solution

  • The issue you are facing now is an interesting thing. Before diving into the answer, lets understand the root cause of the issue.

    Understanding the Root Cause of the Issue The challenge you're facing stems from the fact that when a variable is passed to innerHTML, it gets appended to the div at runtime, after the build has been generated and during component rendering. The Angular build output is a JavaScript bundle, and when the inner HTML is executed, the Angular logic fails because the browser can only understand HTML, JS, and CSS. Specifically, the MatTooltip attribute, which is an Angular-specific feature, cannot be interpreted by the browser, leading to the loss of its functionality.

    Solution To circumvent this limitation, it's essential to separate the tooltip and inner HTML. Instead, try the following approach:

      toolTip="TooltipText"
      variable="<b>Text</b>"
    
    
    <div [matTooltip]="toolTip" [innerHTML]="variable">