本文介绍了在 Angular 中,是否可以在运行时创建的元素上应用 MatTooltip?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FullCalendar(角度版本),我想在资源列表上添加一个图标,当鼠标悬停时,显示 Angular 的 MatTooltip.现在的问题是使用 element.setAttribute('matTooltip') 并没有削减它.它正在转换为 mattooltip ,这将不起作用.

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.

所以我在想是否有可能在新的 HTMLDomElement 上实例化 matTooltip 的方法

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

上面的代码产生一个像这样的 html 元素:

The code above results to an html element like this:

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

我希望 span 元素在悬停时显示工具提示.

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

推荐答案

Anil Kumar Arya 指出我在正确的方向上引导我到这个post.

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

我能够使用 Angular 的 ComponentPortal 将一个组件(包含我需要的工具提示)附加到 DOM,就像这样:

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

这篇关于在 Angular 中,是否可以在运行时创建的元素上应用 MatTooltip?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 23:37