In Angular, is it possible to apply MatTooltip on an element that was created on runtime?

南楼画角 提交于 2020-01-03 04:28:06

问题


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.


回答1:


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




回答2:


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);
}


来源:https://stackoverflow.com/questions/56862498/in-angular-is-it-possible-to-apply-mattooltip-on-an-element-that-was-created-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!