【问题标题】:create angular component tooltip programmatically以编程方式创建角度组件工具提示
【发布时间】:2019-09-27 14:07:29
【问题描述】:

当我悬停一个 svg 元素时应该显示一个工具提示。

我希望工具提示是一个角度组件,以便于创建 UI。

限制是 svg 元素是以编程方式创建的,所以我不知道如何为动态组件渲染创建模板引用。

我的问题是如何构建一个角度组件作为动态 svg 元素的工具提示?

这是 stackblitz 上的 sample。我写了动态组件的代码。现在我应该在悬停圆圈时动态渲染它。

@ViewChild('cont', { static:true,read: ViewContainerRef }) entry: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
@ViewChild('svg', { static: true }) svg: ElementRef

ngAfterViewInit() {
  let circle= document.createElementNS('http://www.w3.org/2000/svg','circle')
  circle.setAttribute('r','40');
  circle.setAttribute('cx','50');
  circle.setAttribute('cy','50');
  //let cont= document.createAttributeNS('http://www.w3.org/2000/svg','#cont')
  //circle.setAttribute('#cont','test')
  this.svg.nativeElement.appendChild(circle)
  this.entry.clear();
  const factory = this.resolver.resolveComponentFactory(TooltipComponent);
  const componentRef = this.entry.createComponent(factory);

}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您可以通过创建自定义组件或直接在 SVG 上使用工具提示来添加它。无论哪种方式,您都希望使用 RxJS 直接观看 SVG 或圆形元素的 mouseovermouseout 事件。

    你可以在这个分叉的堆栈闪电战中看到一个例子。

    https://stackblitz.com/edit/angular-9vgjjl-7qmneg?file=app%2Ftooltip-overview-example.ts

    【讨论】:

    • 哇,rxjs 的威力 .. 但是这种方法有它的局限性:如果 svg 包含其他元素,则工具提示将不会针对相关圈子stackblitz.com/edit/angular-9vgjjl-vtvjqu?file=app/…
    • 确实如此,因此您可以直接定位 svg。但是,如果您这样做,您将获得整个 svg 的工具提示;不仅仅是你的一个元素。由于您的问题是针对 SVG 圈子,所以我认为这是最好的。如果您想看到这一点,请将 fromEvent 方法中的 circle 更改为 this.svg.nativeElement。这是我首先做的。此外,它仍然适用于目标圈子,只是您的第二个圈子与第一个圈子重叠,因此有一小块区域无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 2016-01-17
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多