2

I'm using FullCalendar (angular version) and I wanted to add a glyphicon on the resources list that when hovered, shows angular's MatTooltip. The issue now is that using element.setAttribute('matTooltip') is not cutting it. It's getting converted to mattooltip which won't work.

So I was thinking if there is a possible way of instantiating matTooltip on new HTMLDomElement

let departmentInfoSpan = document.createElement('span');
    departmentInfoSpan.setAttribute('matTooltip', 'sample tooltip');

The code above results to an html element like this:

<span mattooltip="sample tooltip"><span>?</span></span>

I was expecting the span element to be showing the tooltip when hovered.

Dreadnaut
  • 107
  • 1
  • 10

2 Answers2

3

Its not working because angular at compile time reads matTooltip which added there along with CSS and other attributes to make it working and this compilation action is missing at run time.

So, If you want to add tooltip dynamically, there are other alternative solution to it

1.Use *ngIf directive to determine the element to display .

For Example:

<span matTooltip="Yes tooltip" *ngIf="show"></span>
<span matTooltip="No tooltip" *ngIf="!show"></span>

2.Create your custom directive for tooltip

Anil Arya
  • 3,100
  • 7
  • 43
  • 69
  • I've been trying to avoid creating my custom directive but I was left no choice. Though I didn't make my own, I used a component. Thanks for this – Dreadnaut Jul 04 '19 at 03:31
0

Anil Kumar Arya pointed me in the right direction which led me to this post.

I was able to append a component (that contained the tooltip that I needed) to the DOM using Angular's ComponentPortal just like so:

import { ComponentFactoryResolver, ApplicationRef } from '@angular/core';
import { ComponentPortal, DomPortalHost } from '@angular/cdk/portal';

constructor(
    protected componentFactoryResolver: ComponentFactoryResolver,
    protected appRef: ApplicationRef,
    protected injector: Injector
) {}
...

myfunction (): void {
    let bodyPortalHost = new DomPortalHost(
      eventRenderInfo.el.querySelector('.fc-content'), // Target the element where you wish to append your component
      this.componentFactoryResolver,
      this.appRef,
      this.injector);

    let componentToAppend = new ComponentPortal(MyComponentThatHasTheElementWIthTooltip);
    let referenceToAppendedComponent = bodyPortalHost.attach(componentToAppend);
}
Dreadnaut
  • 107
  • 1
  • 10