Angular 2 Material tooltip with HTML content in angular

Viewed 29319

I am trying to bind the HTML strings into angular 2 tool tip. But it's rendering as HTML it showing as a plain string. Is there any way to do render string as an HTML.

Here is my code:

In View:

 <span class="icon-status" mdTooltip="{{value.status}}"></span>

Component:

value.status = this.sanitizer.bypassSecurityTrustHtml(this.getStatusTemplate(value.status));


  getStatusTemplate(status: IIconStatus): string{
let HTML =`
  <div>Event Title</div>
  <div class="">
    <table>
      <thead>
        <th>User</th>
        <th>User</th>
        <th>User</th>
        <th>User</th>
      </thead>
    </table>
  </div>
`;
return HTML;}

Thanks in advance.

6 Answers

Bad news for us: HTML is not supported in angular material tooltips and for now, they don't have intentions to support it. Here more info.

It's not well tested, but I did it by defining setter for "message" property on TooltipComponent(app.component.ts)

Object.defineProperty(TooltipComponent.prototype, 'message', {
   set(v: any) {
       const el = document.querySelectorAll('.mat-tooltip');

       if (el) {
           el[el.length - 1].innerHTML = v;
       }
   },
});

html

<div [matTooltipClass]="'right'"
     [matTooltip]="aboveTemplate"
     matTooltipPosition="right">
    Right
</div>

ts

aboveTemplate = `<div class="color-red">Top Template<button style="background: white; color: black">Press me</button></div>`;

result

enter image description here

Material, as opposed to bootstrap, does not have anything like a popover (it has tooltip which is just text, no HTML). I think based on the guides for this use-case you are supposed to use a dialog instead.

What you are looking for is a Popover. And as said, it doesn't exist now and it's not possible with tooltips.

Answer from @jelbourn, Angular member team:

When designing the tooltip we deliberately decided not to support this. The Material Design spec is rather prescriptive about only text appearing in tooltips. Rich content also presents a challenge for a11y.

Source: https://github.com/angular/components/issues/5440#issuecomment-313740211

You can find the feature request for popover here.

Until an official release from Material team you can use an alternative. Here are some examples:


Edit: If you need simple customization (changing background-color, color, font-size...) for the whole tooltip you can read this post.

How to test passed it by jest?

Object.defineProperty(TooltipComponent.prototype, 'message', {
   set(v: any) {
       const el = document.querySelectorAll('.mat-tooltip');

       if (el) {
           el[el.length - 1].innerHTML = v;
       }
   },
});
Related